Groot
Groot

Reputation: 171

Regex to not allow special character without prefix or suffix

I was writing regex for the following validate a string. I wrote the following regex.

^[^\s]+[a-z]{0,}(?!.* {2})[ a-zA-z]{0,}$

it validates for

  1. No space in beginning.
  2. no two consecutive space allowed.
  3. The problem is it allows a single special character. it should not allow a special character unless it is suffixed or prefixed with alpha-numeric character.

Examples:

# -> not allowed.

#A or A# or A2 or 3A is allowed.

Upvotes: 2

Views: 975

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

One option is to assert that the string does not contain a single "special" char or 2 special chars next to each other using a negative lookahead.

^(?!.*[^a-zA-Z0-9\s][^a-zA-Z0-9\s])(?!.*(?:^| )[^a-zA-Z0-9\s](?!\S))\S+(?: \S+)*$

Explanation

  • ^ Start of string
  • (?! Negative lookahead, assert that what is at the right does not contain
    • .*[^a-zA-Z0-9\s][^a-zA-Z0-9\s] match 2 chars other than a-zA-Z0-9 or a whitespace char next to each other
  • ) Close lookahead
  • (?! Negative lookahead, assert that what is at the right does not contain
    • .*(?:^| )[^a-zA-Z0-9\s](?!\S) Match a single char other than a-zA-Z0-9 or a whitespace char
  • ) Close lookahead
  • \S+(?: \S+)* Match 1+ non whitespace chars and optionally repeat a space and 1+ non whitespace chars
  • $ End of string

Regex demo

Upvotes: 2

Jimmy
Jimmy

Reputation: 51

Please omit the '$' symbol from the regex because it represents the end of the sentence.

^[^\s]+[a-z]{0,}(?!.* {2})[ a-zA-z]{0,}

So when applying the above regex to the following, it finds only '# '.

#A A# A2 3A

Upvotes: 1

Related Questions