Gonzalo
Gonzalo

Reputation: 1

Regular expression in Java to match a String containing + character

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?

Upvotes: 0

Views: 124

Answers (1)

Brett Ryan
Brett Ryan

Reputation: 28255

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

^[+-](id|originId)$

Upvotes: 1

Related Questions