【发布时间】:2014-01-02 16:39:07
【问题描述】:
我的程序中有一个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”?
【问题讨论】:
-
你有什么问题?
-
如果用户输入了一个类似“1 12 13 14”的字符串,是需要单独处理(1、12、13、14)还是读取为一个值1121314?
-
@Odrai 我将分别处理它们。
-
@gleng 我更新了我的问题,希望对您有所帮助。
-
在这里regexpal.com 构建和测试你的正则表达式并尝试这个表达式...这应该让你开始:^[\d\W]*$
标签: c# wpf regex string textbox