Reputation: 3000
I have this regular expression
([A-Z], )*
which should match something like
test,
(with a space after the comma)
How to I change the regex expression so that if there are any characters after the space then it doesn't match. For example if I had:
test, test
I'm looking to do something similar to
([A-Z], ~[A-Z])*
Cheers
Upvotes: 21
Views: 82156
Reputation: 112915
Use the following regular expression:
^[A-Za-z]*, $
Explanation:
^
matches the start of the string.[A-Za-z]*
matches 0 or more letters (case-insensitive) -- replace *
with +
to require 1 or more letters.,
matches a comma followed by a space.$
matches the end of the string, so if there's anything after the comma and space then the match will fail.As has been mentioned, you should specify which language you're using when you ask a Regex question, since there are many different varieties that have their own idiosyncrasies.
Upvotes: 35
Reputation: 111940
^([A-Z]+, )?$
The difference between mine and Donut is that he will match ,
and fail for the empty string, mine will match the empty string and fail for ,
. (and that his is more case-insensitive than mine. With mine you'll have to add case-insensitivity to the options of your regex function, but it's like your example)
Upvotes: 3
Reputation: 1024
I am not sure which regex engine/language you are using, but there is often something like a negative character groups [^a-z]
meaning "everything other than a character".
Upvotes: 1