Search code examples
regexregex-lookaroundsregex-groupregex-greedy

Regex for failing double dashes in a string


I have a naming convention for tokens (simple strings) which has to be followed. Double dashes are the separator of different parts. For example:

  • ActiveDirectory--User--<LastName>--Password
  • ActiveDirectory--App--<DisplayName>--Secret

Now I want to check if a token is following the naming convention.

The naming convention says that the token must only contain a-z, A-Z, 0-9 or dashes (-). Double dashes are not allowed inside <CustomName>.

The regex

^ActiveDirectory--User--([a-zA-Z0-9-]*)--Password$

works fine if you have the following token as input

ActiveDirectory--User--Smith--Password,

but it doesn't check double dashes like

ActiveDirectory--User--Sm--ith--Password.

In that case, the word "Sm--ith" would be a group of my match. The desired state should be, that there is no match.

I already tried to use the negated Look Ahead (negation) in combination with Back-References. But I have to become a regex expert before solving such a complex problem.

How do I solve this problem?


Solution

  • If your token can have leading and trailing -, you may use

    ^ActiveDirectory--User--((?:(?!--)[a-zA-Z0-9-])*)--Password$
    

    See the regex demo. Here, (?:(?!--)[a-zA-Z0-9-])* matches 0 or more ASCII letters or digits or hyphens, but does not match a char if together with the next char it is equal to --.

    If your token cannot start/end with a -, use

    ^ActiveDirectory--User--([a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)--Password$
    

    See another demo. Here, [a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)* matches 1+ letters/digits and then 0 or more repetitions of - and 1+ letters/digits.