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?
use this regex
^[0-9+#*\[\]]+$