Search code examples
javaregex

Regex should not match for two or more consecutive dashes


I have the following regex:

\p{Alpha}[\p{Alnum}-]+\p{Alnum}

With this, the text should start with an alpha character and could be followed by alphanumerics and dashes.

But I don't want to have two or more consecutive dashes. What is the right regex that I can use for this case?


Solution

  • You may consider this regex solution:

    ^\p{Alpha}\p{Alnum}*(?:-\p{Alnum}+)*$
    

    RegEx Demo

    RegEx Details:

    • ^: Start
    • \p{Alpha}: Match an alphabet
    • \p{Alnum}*: Match 0 or more alphanumeric characters
    • (?:-\p{Alnum}+)*: Match - followed by 1+ of alphanumeric characters. Repeat this group 0 or more times
    • $: End