user1752082 user1752082 - 1 year ago 78
Java Question

Restrict consecutive characters using Java Regex

I need to allow alphanumeric characters:

in the given string. But I need to restrict consecutive

For example:

should be valid.

should be invalid.

Currently I'm using

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

Answer Source

You may use grouping with quantifiers:


See the regex demo


  • ^ - 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:


See the demo here


  • ^ - 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/.?-]+$".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download