Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate that a string contains only 0 - 9, +, #, *, [ and ]

In my c# application, I need to validate strings to ensure that they only contain the following:

  • 0 - 9
  • +
  • #
  • *
  • [
  • ]

When my user edits a string field in the cell of a DataGridView control, I need to validate the value. My CellValidating event handler currently looks like this:

if (!Regex.IsMatch(e.FormattedValue.ToString(), @"\A\b[0-9]+\b\Z"))
{
    // notify the user that the string is invalid and cancel validation
    e.Cancel = true;
}

This seems to work for 0 - 9 but I've yet to get a regex working that includes all the metacharacters I need. I tried adding one metacharacter at a time to the existing regex but it doesn't work. For example...

if (!Regex.IsMatch(e.FormattedValue.ToString(), @"\A\b[0-9#]+\b\Z"))

...doesn't allow # like I thought it would. Escaping it didn't make a difference either. Can anyone shed some light on this for me?

like image 470
bmt22033 Avatar asked Dec 20 '12 15:12

bmt22033


People also ask

How do I check if a string has 0 9?

strng. contains("[0-9]+") returns true only if the string literally contains [0-9]+ .

What is the regex represent 0 9?

The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.

What does the regex 0 9 ]+ do?

In this case, [0-9]+ matches one or more digits. A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier). This regex matches any numeric substring (of digits 0 to 9) of the input.


1 Answers

use this regex ^[0-9+#*\[\]]+$

like image 161
burning_LEGION Avatar answered Sep 18 '22 17:09

burning_LEGION