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.
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");
}
}
您需要添加()
以使正则表达式正确锚定,否则您的示例将匹配,因为正则表达式仅检查字符串开头是否有1到5位数字-以后可能会出现任何数字。
@"^(\d{1,5}|\d{0,5}\.\d{1,2})$"
The reason it isn't working is because you haven't encompassed your Regular Expression within ()
. Without that identifier it isn't able anchor your syntax correctly.
You would want your Expression to look like this:
@"^(\\d{1,5}|\\d{0,5}\\.\\d{1,2})$
Keep in mind you may have also added additional complexity to your 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. 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.
Hopefully that helps, I see a Grey 1 Answer Box so someone else posted so you should easily find a resolution Calvin.
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.