Reputation: 171
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
Examples:
#
-> not allowed.
#A
or A#
or A2
or 3A
is allowed.
Upvotes: 2
Views: 975
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 stringUpvotes: 2
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