简体   繁体   中英

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 numberExpression = new Regex(@"(?<Number>\d+)");

This current works fine for input strings like "1", "100", "1a", "a1", etc....

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.

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".

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.

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