Susan
Susan

Reputation: 1832

Exclude characters from REGEX expression

Regex expression:

^[a-z A-Z0-9-/().,@&#*!%:-]{0,100}

How can I add an exclusion for the '$' and '+' signs? I tried the following but it didn't work. It excluded the first excluded character it came to and every other character after that (including characters I wish to include).

^[a-z A-Z0-9-/().,@&#*!%:-][^$+]{0,100}

Upvotes: 0

Views: 142

Answers (2)

revo
revo

Reputation: 48711

You already made $ and + sign excluded when didn't include them in your char class:

[a-z A-Z0-9\-\/().,@&#*!%:]{0,100}

As the way I understood, you don't need ^ to check the beginning of the input. also you'd better to escape - as it's in the middle of class and remove the one that's at the end, as well as / that may be used as delimiter.

Live demo

Upvotes: 0

Enissay
Enissay

Reputation: 4953

You can use a negative lookahead wich checks if the input doesnt contain any $ or +, then selects the appropriate characters:

/^(?!.*?[$+])[a-z A-Z0-9-\/().,@&#*!%:-]{0,100}/

Live DEMO

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
    [$+]                     any character of: '$', '+'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  [a-z A-Z0-9-             any character of: 'a' to 'z', ' ', 'A' to
  \/().,@&#*!%:-           'Z', '0' to '9', '-', '\/', '(', ')', '.',
  ]{0,100}                 ',', '@', '&', '#', '*', '!', '%', ':', '-
                           ' (between 0 and 100 times (matching the
                           most amount possible))

Upvotes: 3

Related Questions