0

I'm using annotation javax.validation.constraints.Pattern to validate the sort parameter. The value of this parameter must be: +id or +originId for ascending, and -id or -originId for descending.

The syntax of this parameter can not be modified.

@Valid @Pattern(regexp= SORT_REGEXP, message = SORT + NOT_VALID) @RequestParam(name = SORT, required = false) String sort, 

This is what I have as my regular expression:

^[+-]id$|^[+-]originId$ 

I have also tried escaping the plus sign + like:

^[\\+-]id$|^[\\+-]originId$ 

If I use the -id or the -originId, it's been validated but when I use the + it says that it's not matching the pattern.

How to match the plus-sign with a regular expression?

3

1 Answer 1

1

Your pattern can be simplified by specifying the boundaries outside your match and using a group.

^[+-](id|originId)$ 
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your improvement suggestion! Any idea of how to solve the issue with the + character?
This should solve the issue with the + character. Tested with Pattern.compile("^[+-](id|originId)$").matcher("+id")
I'm sorry, but if I try to send the request with +id and using that regex is still saying that doesn't match. I know it should work but is failing...
The regex is good, the problem is elsewhere. How do you send a request? Remember, that for example in an url a simple plus character is interpreted as a space and should be escaped as %2B
Thanks Alex! That was the problem. I try with %2B instead of + and works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.