[英]Regex for textbox to accept only numbers, comma and not 0, decimal or special characters
I am looking for a regex to accept only numbers and comma but not 0,decimal,special characters,negative numbers and white-space between the numbers.It can allow White-space at the start and end of the value.Also It should allow 0 for 10,100,20 but I don't want the textbox to allow a single digit zero. 我正在寻找一个正则表达式,仅接受数字和逗号,但不接受0,十进制,特殊字符,负数和数字之间的空格。它可以在值的开头和结尾处允许空格。也应允许10,100,20为0,但我不希望文本框允许单个数字零。
I have tried multiple options but I couldn't find one that solve my problem. 我尝试了多种选择,但是找不到解决我问题的选择。
string testAnswer = textbox.value;
Regex answerRegex = new Regex(@"\s+(?<!-)[1-9][0-9,]*\s+");
if (testAnswer.Contains(","))
{
testAnswer = testAnswer.Replace(",", "");
Response.Write(testAnswer);
}
Match answerMatch = answerRegex.Match(testAnswer.Trim());
if (testAnswer == String.Empty || !answerMatch.Success)
{
valid = false;
answer.CssClass = "error";
}
else
{
answer.CssClass = "comp";
}
I think this will do what you want. 我认为这会做您想要的。
(\s+|^)(?<!-)[1-9][0-9,]*(\s+|$)
EDIT: I think I figured out your problem in your code. 编辑:我想我在您的代码中找到您的问题。 You're only checking based on
Success
property. 您仅根据“
Success
属性进行检查。 You need to check answerMatch.Groups
in your code as well. 您还需要在代码中检查
answerMatch.Groups
。
If you checked answerMatch.Groups[0]
when you enter 7+9
string, you will realize that the match only matches 7
and discards the rest (+9) of the string. 如果在输入
7+9
字符串时选中了answerMatch.Groups[0]
,您将意识到匹配项仅匹配7
并丢弃字符串的其余部分(+9)。
Ok, I have tested this more extensively and I'm sure that this now works. 好的,我已经对此进行了更广泛的测试,并且我确信现在可以使用了。 I've modified your code a little bit so I can use it to demonstrate my test.
我对您的代码做了一些修改,以便可以用它来演示测试。
string testAnswer = "7 7+9700 700 007 400 -7 8";
bool valid = true;
string retVal = "";
Regex answerRegex = new Regex(@"(\s+|^)(?<!-)[1-9][0-9,]*(\s+|$)");
if (testAnswer.Contains(","))
{
testAnswer = testAnswer.Replace(",", "");
retVal = testAnswer;
}
MatchCollection answerMatch = answerRegex.Matches(testAnswer.Trim());
if (testAnswer == String.Empty || answerMatch.Count <= 0)
{
valid = false;
retVal = "error";
}
else
{
retVal = "comp";
foreach(Match m in answerMatch) {
Console.WriteLine(m.Groups[0].Value);
}
}
testAnswer
holds my test string to be checked. testAnswer
持有我要检查的测试字符串。 The output of the test program is as follows: 测试程序的输出如下:
7
700
400
8
That output proves that it rejects negative numbers as well as special characters within the number string. 该输出证明它拒绝负数以及数字字符串中的特殊字符。
As for the regex string (\\s+|^)(?<!-)[1-9][0-9,]*(\\s+|$)
here is the breakdown: 至于正则表达式字符串
(\\s+|^)(?<!-)[1-9][0-9,]*(\\s+|$)
如下:
If I got you right it should be 如果我说对了,应该是
Regex answerRegex = new Regex(@"^[1-9][0-9]*$");
The *
instead of the +
lets pass 1, 10, etc. 用
*
而不是+
传递1、10等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.