使用正则表达式进行 wpf 文本框验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15775938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
wpf textbox validation with regex
提问by Calvin
I have a textbox in which I'm using the event TextChanged to check if the string is valid with RegEx and show a messagebox if it isnt. When testing the regex I have with online regex tool such as http://regexpal.com/, it seems to be working fine. But when I run my code, it's not working as expected. I'm never seeing the messagebox show up. Any help would be appreciated. My regex is suppose to check any digits from 0-5 before the "." with two decimals if any.
我有一个文本框,我在其中使用事件 TextChanged 检查字符串是否对 RegEx 有效,如果无效则显示消息框。当我使用在线正则表达式工具(例如http://regexpal.com/ )测试正则表达式时,它似乎工作正常。但是当我运行我的代码时,它没有按预期工作。我从来没有看到消息框出现。任何帮助,将不胜感激。我的正则表达式应该在“.”之前检查 0-5 之间的任何数字。如果有的话,保留两位小数。
private void txtValInput_TextChanged(object sender, TextChangedEventArgs e)
{
string input = (sender as TextBox).Text; //1234567
if(!Regex.IsMatch(input, @"^\d{1,5}|\d{0,5}\.\d{1,2}$"))
{
MessageBox.Show("Error!, check and try again");
}
}
采纳答案by MikeM
You need to add the ()so the regex is properly anchored, otherwise your example matches because the regex is only checking whether there are one to five digits at the start of the string - anything could come after.
您需要添加 ,()以便正则表达式正确锚定,否则您的示例匹配,因为正则表达式仅检查字符串开头是否有 1 到 5 个数字 - 后面可能会出现任何内容。
@"^(\d{1,5}|\d{0,5}\.\d{1,2})$"
回答by Greg
The reason it isn't working is because you haven't encompassed your Regular Expressionwithin (). Without that identifier it isn't able anchor your syntax correctly.
它不起作用的原因是因为您没有将正则表达式包含在(). 如果没有那个标识符,它就不能正确地锚定你的语法。
You would want your Expressionto look like this:
你会希望你的Expression看起来像这样:
@"^(\d{1,5}|\d{0,5}\.\d{1,2})$
@"^(\d{1,5}|\d{0,5}\.\d{1,2})$
Keep in mind you may have also added additional complexity to your Expression.
请记住,您可能还为Expression增加了额外的复杂性。
To elaborate:
详细说明:
^: Will grab the first character or line.\d: Will grab all the numeric characters.$: Will stop at end of line or last character.
^: 将抓取第一个字符或行。\d: 会抓取所有的数字字符。$: 将在行尾或最后一个字符处停止。
I'd like to take a second with that second one. If you actually do \d+it will grab all numeric characters and all that precede afterwards. Which may make your request slightly easier; but I'm unsure of what you are searching.
我想花点时间看第二个。如果你真的这样做了,\d+它会抓取所有数字字符以及之后的所有字符。这可能会使您的请求稍微容易一些;但我不确定你在搜索什么。
Hopefully that helps, I see a Grey 1 Answer Boxso someone else posted so you should easily find a resolution Calvin.
希望这会有所帮助,我看到了一个灰色的 1 个答案框,所以其他人发布了这样你应该很容易找到卡尔文的解决方案。

