简体   繁体   English

正则表达式匹配仅包含数字而不包含字母的字符串

[英]Regular expression to match a string that contains only numbers, not letters

My code is currently using the following Regex expression which matches on numbers: 我的代码目前正在使用以下与数字匹配的Regex表达式:

Regex numberExpression = new Regex(@"(?<Number>\d+)");

This current works fine for input strings like "1", "100", "1a", "a1", etc.... 此电流适用于输入字符串,如“1”,“100”,“1a”,“a1”等....

But I want to change it so it does NOT match when the input string contains a letter, so "1", "100" would match, but "1a", "a1", would not. 但我想改变它,因此当输入字符串包含一个字母时它不匹配,所以“1”,“100”将匹配,但“1a”,“a1”不会。

Can anyone help, I know this is a simple regular expression question but I can't get my head around the forward and backward looking. 任何人都可以提供帮助,我知道这是一个简单的正则表达式问题,但我不能让我的头脑向前和向后看。 I have tried: 我努力了:

Regex numberExpression = new Regex(@"(?<Number>^![a-zA-Z]\d+![a-zA-Z])");

but that didn't work, and fails to match any of the above input. 但这不起作用,并且无法匹配任何上述输入。

Regex is overkill. 正则表达式是矫枉过正。 Try this: 尝试这个:

input.All(char.IsDigit);

You are trying to do it the hard way, by looking for a numeric substring of the input, and then looking to see that there isn't anything before or after that substring. 您正在尝试通过查找输入的数字子字符串,然后查看该子字符串之前或之后没有任何内容来进行艰难的操作。

The easy way to do it is to force the regular expression to either match the entire input string or nothing: 简单的方法是强制正则表达式匹配整个输入字符串或什么都不是:

Regex numberExpression = new Regex(@"^\d+$");

where "^" means "beginning of line" and "$" means "end of line". 其中“^”表示“行首”,“$”表示“行尾”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM