Regex for disallowing commas
Try changing your regex to:
"^[^,]+$"
Let's say we're matching against "Hello, world"
The first ^
asserts that we're at the beginning of the string. Next [^,]
is a character class which means "Any character except ,
." +
next to something means "Match this one or more times." Finally, $
asserts that we're now at the end of the string.
So, this regular expression means "At the start of the string (^
), match any character that's not a comma ([^,]
) one or more times (+
) until we reach the end of the string ($
).
This regular expression will fail on "Hello, world"
- everything will be fine for H
, e
, l
, l
, and o
, until we reach the comma - at which point the character class fails to match "not a comma".
For some great tutorials about regular expressions, you should read up on http://www.regular-expressions.info/
Daniel
Updated on June 06, 2022Comments
-
Daniel almost 2 years
I'm trying to disallow commas in a string entered into a textbox. Here is what I have so far:
[RegularExpression (@"?[^,]*$", ErrorMessage = "Commas are not allowed in the subtask title. Please remove any and try again")]
This is probably my 5th or 6th attempt, nothing so far has worked. Any help would be appreciated.
-
Daniel almost 10 yearsSo what does the * do? In @avinashRaj response, he used the * character which did exactly what I wanted. What's the difference between that and +?
-
Rickkwa almost 10 years@Daniel * is 0 or more, + means at least 1
-
Kelvin almost 10 years
*
means 0 or more times - or in other words, "this is optional". For example, if you wanted to match "http" and "https" and didn't care which it is as long as both match, you would use"https?"
("matchh
, matcht
, matcht
, matchp
, and matchs
if it's there but don't worry if it's not") -
Daniel almost 10 yearsSo why does the * work at all? If it is 0 or more, shouldn't it be considering the whole string invalid no matter what the input is?
-
Daniel almost 10 yearsSo it seems that the + is actually the correct way to accomplish this then? The * could have some unintended consequences?
-
Kelvin almost 10 yearsThe
*
works because[^,]*
means "Match anything that's not a comma 0 or more times" - so, because we have^
and$
matching the start and end of the string, we need everything between the start and end of the string to be anything that's not a comma. The only literal difference, in this case, is that*
will allow an empty string, whereas+
demands that it's at least one character long.