Regex initialization issues

I am working with slightly outdated code, and I am trying to add a new regular expression to the validator counter, for our purposes, designated as "URL". As far as I understand, each part of the counter can be called in a separate regular expression. Anyway, here is what I have (and others follow, therefore, the final comma):

URL("[a-zA-Z0-9\r#;?-\'.:,!/\\s]{1,250}", "Up to 250 letters (upper and lower case), numbers, #, ;, ?, -, ', ., :, comma, !, /, blankspace and carriage return"), 

I did a simple JUnit test to make sure that it works correctly. This is not true.

 Caused by: java.util.regex.PatternSyntaxException: Illegal character range near index 15 [a-zA-Z0-9 #;?-'.:,!/\s]{1,250} ^ 

I am trying to limit the input of a type URL from 1 to 250 characters, which I thought I was doing, but Eclipse seems to be offended by this comma (I assume the comma is index 15). What am I doing wrong?

+4
source share
1 answer

Probably the problem is here:

 ?-' 

Is this interpreted as a range from a character ? up to the character ' , which is invalid because ? has a code point 63, and ' has a code point 39. Ranges must go from low to high. But you probably did not want to have a range. I assume you wrote a literal hyphen.

To fix the error, try a hyphen:

 ?\\-' 

The reason the error message indicator is in the wrong place is because of \r in the regular expression. If you replace the new line with another character, the indicator will display with the wrong range:

  [a-zA-Z0-9 _ #;? - '.:,! / \ s] {1,250}
                ^

You can also use \\r instead of \r so that the error message is printed correctly.

+8
source

Source: https://habr.com/ru/post/1342720/


All Articles