Regex for disallowing commas

10,577

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/

Share:
10,577
Daniel
Author by

Daniel

Updated on June 06, 2022

Comments

  • Daniel
    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
    Daniel almost 10 years
    So 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
    Rickkwa almost 10 years
    @Daniel * is 0 or more, + means at least 1
  • Kelvin
    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?" ("match h, match t, match t, match p, and match s if it's there but don't worry if it's not")
  • Daniel
    Daniel almost 10 years
    So 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
    Daniel almost 10 years
    So it seems that the + is actually the correct way to accomplish this then? The * could have some unintended consequences?
  • Kelvin
    Kelvin almost 10 years
    The * 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.