Limit consecutive characters with Java Regex

I need to allow alphanumeric characters "?","." , "/", and "-"in this line. But I need to limit only sequential ones -.

For instance:

  • www.google.com/flights-usa must be valid

  • www.google.com/flights--usa must be invalid

I am currently using ^[a-zA-Z0-9\\/\\.\\?\\_\\-]+$.

Please suggest me limit only serial -.

+4
source share
3 answers

You can use grouping with quantifiers:

^[a-zA-Z0-9/.?_]+(?:-[a-zA-Z0-9/.?_]+)*$

Watch the regex demo

More details

  • ^ - beginning of line
  • [a-zA-Z0-9/.?_]+ - 1 , ( [\w/.?]+)
  • (?:-[a-zA-Z0-9/.?_]+)* - ((?:...)*):
    • - - hyphen
    • [a-zA-Z0-9/.?_]+ - .
  • $ - .

:

^(?!.*--)[a-zA-Z0-9/.?_-]+$
 ^^^^^^^^^

  • ^ -
  • (?!.*--) - lookahead, , regex -- 0+,
  • [a-zA-Z0-9/.?_-]+ - 1 ,
  • $ - .

, [a-zA-Z0-9_]= \w, Pattern.UNICODE_CHARACTER_CLASS. , "^[\\w/.?]+(?:-[\\w/.?]+)*$", - "^(?!.*--)[\\w/.?-]+$".

+3

, , :

^(?:[a-zA-Z0-9\/\.\?\_]|(?<!-)-)+$

|, .. (?<!-)-, ", ".

-

+1

, , .

^([a-zA-Z0-9\/\.\?\_]|\-([^\-]|$))+$

, [a-zA-Z0-9\/\.\?\_], , , . , \-([^\-]|$), , , .

.

0

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


All Articles