regexregex-group

Regex with one special characters avoiding periods and parentheses


I am working with a Regex to validate a string with the following requeriments:

  1. It does not start with special characters.
  2. It can countains numbers, letters and special characters, with the exception of periods and parentheses.
  3. Special characters can appear 1 time only.

The Regex i have is this one:

/^[a-zA-Z0-9]+(?!\S*([\W_.()])\S*\1{1,})\S*$/

The regex is not working fine, because it continues accepting periods and parentheses.

Would you know how can achieve the above requeriments?

Thanks in Advance.


Solution

  • I think you don't even need a lookahead to check for one special character. If you define those as [not whitespace, no digit or letter, no dot, no parentheses] that would be [^\s\da-z.)(].

    ^[^\W_]+[^\s\da-z.)(]?[^\W_]*$
    

    See this demo at regex101 - Use with i-flag (prepend (?i) if inline flags are supported).
    [^\W_] is a short for alphanumeric character, one or more at start and any amount at end.


    Or if you want to allow multiple special characters but none more than once with lookahead:

    ^[^\W_]+(?:([^\s\da-z.)(])(?!.*\1)[^\W_]*)*$
    

    Demo at regex101 - The special character is captured to the first group, checked if \1 reoccurs. Using a non-capture group for repetition of specials followed by any amount of alphanumeric.