Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

c# - 正则表达式仅用于数字(Regex for numbers only)

I haven't used regular expressions at all, so I'm having difficulty troubleshooting.

(我根本没有使用过正则表达式,因此我很难进行故障排除。)

I want the regex to match only when the contained string is all numbers;

(我希望正则表达式仅在包含的字符串为全数字时才匹配;)

but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321".

(但是在下面的两个示例中,它匹配包含所有数字和等号(例如“ 1234 = 4321”)的字符串。)

I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions.

(我敢肯定有一种方法可以改变这种行为,但是正如我所说,我从未真正对正则表达式做过很多事情。)

string compare = "1234=4321";
Regex regex = new Regex(@"[d]");

if (regex.IsMatch(compare))
{ 
    //true
}

regex = new Regex("[0-9]");

if (regex.IsMatch(compare))
{ 
    //true
}

In case it matters, I'm using C# and .NET2.0.

(万一重要,我使用的是C#和.NET2.0。)

  ask by Timothy Carter translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the beginning and end anchors.

(使用开始和结束锚点。)

Regex regex = new Regex(@"^d$");

Use "^\d+$" if you need to match more than one digit.

(如果您需要匹配多个数字,请使用"^\d+$" 。)


Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ?????????? .

(请注意, "\d"将匹配[0-9]和其他数字字符,例如东部阿拉伯数字?????????? 。)

Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.

(使用"^[0-9]+$"将匹配项限制为仅阿拉伯数字0-9。)


If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist 's comprehensive guide to parsing numbers with regular expressions .

(如果您需要包含除数字以外的任何数字表示形式(例如入门的十进制值),请参阅@tchrist综合指南,该指南以正则表达式解析数字 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...