user1752082 user1752082 - 4 months ago 20
Java Question

Restrict consecutive characters using Java Regex

I need to allow alphanumeric characters:

?
,
.
,
/
and,
-
in the given string. But I need to restrict consecutive
-
only.

For example:

www.google.com/flights-usa


should be valid.

www.google.com/flights--usa


should be invalid.

Currently I'm using
^[a-zA-Z0-9\\/\\.\\?\\_\\-]+$

Please suggest to me how to restrict consecutive "-" only.

Answer

You may use grouping with quantifiers:

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

See the regex demo

Details:

  • ^ - start of string
  • [a-zA-Z0-9/.?_]+ - 1 or more characters from the set defined in the character class (can be replaced with [\w/.?]+)
  • (?:-[a-zA-Z0-9/.?_]+)* - zero or more sequences ((?:...)*) of:
    • - - hyphen
    • [a-zA-Z0-9/.?_]+ - see above
  • $ - end of string.

Or use a negative lookahead:

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

See the demo here

Details:

  • ^ - start of string
  • (?!.*--) - a negative lookahead that will fail the match once the regex engine finds a -- substring after any 0+ chars other than a newline
  • [a-zA-Z0-9/.?_-]+ - 1 or more chars from the set defined in the character class
  • $ - end of string.

Note that [a-zA-Z0-9_] = \w if you do not use the Pattern.UNICODE_CHARACTER_CLASS flag. So, the first would look like "^[\\w/.?]+(?:-[\\w/.?]+)*$" and the second as "^(?!.*--)[\\w/.?-]+$".

Comments