Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for disallowing commas

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.

like image 902
Daniel Avatar asked Jul 17 '14 13:07

Daniel


People also ask

How do you match a comma in regex?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.

How do you avoid commas in regex?

To remove the leading and trailing comma from a string, call the replace() method with the following regular expression as the first parameter - /(^,)|(,$)/g and an empty string as the second. The method will return a copy of the string without the leading or trailing comma. Copied!

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


1 Answers

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/

like image 179
Kelvin Avatar answered Nov 15 '22 06:11

Kelvin