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?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Gonzalo
  • 1
  • 1
  • 1
    the regular expression seems to be working: https://ideone.com/oMPWM8 - we need more information – user16320675 Nov 22 '22 at 15:44
  • Related question using `asc` and `desc` instead of mathematical signs: [Spring Data Rest - Sort by multiple properties - Stack Overflow](https://stackoverflow.com/questions/33018127/spring-data-rest-sort-by-multiple-properties/33034533#33034533) – hc_dev Dec 06 '22 at 19:59
  • Within URLs the `+` is usually decoded to space: [url - Why is Spring de-coding + (the plus character) on application/json get requests? and what should I do about it?](https://stackoverflow.com/questions/50270372). See also "Requires URL percent encoding" for Lucene-syntax in [Paging, sorting, filtering and retrieving specific fields in your RESTful API | by Guillaume Viguier-Just | Medium](https://medium.com/@guillaume.viguierjust/paging-sorting-filtering-and-retrieving-specific-fields-in-your-restful-api-a0d289bc574a) – hc_dev Dec 06 '22 at 20:10

1 Answers1

1

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

^[+-](id|originId)$
Brett Ryan
  • 26,937
  • 30
  • 128
  • 163
  • Thanks for your improvement suggestion! Any idea of how to solve the issue with the + character? – Gonzalo Nov 22 '22 at 11:52
  • 1
    This should solve the issue with the `+` character. Tested with `Pattern.compile("^[+-](id|originId)$").matcher("+id")` – Brett Ryan Nov 22 '22 at 12:02
  • 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... – Gonzalo Nov 22 '22 at 12:10
  • 1
    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 – Alex Sveshnikov Nov 22 '22 at 12:31
  • Thanks Alex! That was the problem. I try with %2B instead of + and works. – Gonzalo Nov 22 '22 at 12:42