我的程序中有textBox
,其中包含string
,必须满足一些要求。我问这个问题是找出满足这些要求的最佳方法。
此string
不能为NullOrEmpty
,且必须完全由整数组成。 string
也可以包含空格,这是我的关键点,因为空格不是整数。
这就是我正在使用的(我知道目前可能有点多余):
//I test the string whenever the textBox loses focus
private void messageBox_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(TextBox.Text))
ButtonEnabled = true;
else if (Regex.IsMatch(TextBox.Text, @"^\d+$") == false)
{
//I think my problem is here, the second part of the if statement doesn't
//really seem to work because it accepts characters if there is a space
//in the string.
if (TextBox.Text.Contains(" ") && !Regex.IsMatch(TextBox.Text, @"^\d+$"))
ButtonEnabled = true;
else
{
MessageBox.Show("Illegal character in list.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
ButtonEnabled = false;
}
}
else
ButtonEnabled = true;
}
我从this answer获得了Regex
解决方案。
问题:如何设置此textBox
只接受以下值:
“345 78”或“456”?
答案 0 :(得分:5)
正则表达式似乎很简单。它可能是(具有指定约束)的行:
^([\s\d]+)?$
在LostFocus
处理程序中,您可以使用以下内容:
ButtonEnabled = Regex.IsMatch(TextBox.Text, @"^([\s\d]+)?$");
如果出现以下情况,将启用该按钮:
如果您想要一个也会提取数字的正则表达式,您可以将模式更改为:
^(\s*(?<number>\d+)\s*)*$
并使用number
捕获组。
请注意,第一个模式将匹配仅由空格组成的字符串。