简体   繁体   中英

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?

使用这个正则表达式^[0-9+#*\\[\\]]+$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM