c# 仅用于数字和破折号的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8760924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# Regex for numbers and dash only
提问by Nate Pet
I have the following in my c# code - what I like it to do is to check to see if the expression has numbers or a dash but nothing else. If I type in the letter K along with a dash or number it still accepts it. How do I say just have the express be numbers or a dash:
我的 c# 代码中有以下内容 - 我喜欢它做的是检查表达式是否有数字或破折号,但没有其他内容。如果我输入字母 K 和破折号或数字,它仍然接受它。我怎么说只是让快递是数字或破折号:
Match match = Regex.Match(input, @"[0-9-]");
Note that input is the text that I am passing for evalution.
请注意,输入是我传递给评估的文本。
采纳答案by Hans Ke?ing
Match match = Regex.Match(input, @"^[0-9-]*$");
The ^means that the match should start at the beginning of the input, the $that it should end at the end of the input.
在^该比赛应在输入的起点开始的手段,在$它应该在输入的结束而终止。
The *means that (only) 0 or more numbers or dashes should be there (use +instead for 1 or more).
这*意味着(仅)0 个或多个数字或破折号应该在那里(+用于 1 个或多个)。
回答by Jesse Webb
You need to escape the second dash.
你需要逃避第二次破折号。
Match match = Regex.Match(input, @"[0-9\-]");
I'll admit I didn't try it out, but it should work.
我承认我没有尝试过,但它应该有效。
This will actually only work with one character. If you want it to take more than one character, like "123-5", then change your regex to..
这实际上只适用于一个角色。如果您希望它包含多个字符,例如“123-5”,则将正则表达式更改为..
Match match = Regex.Match(input, @"[0-9\-]+");
回答by mynameiscoffey
Your Regex matches that anydigit or dash exists within the string, try the following:
您的正则表达式匹配字符串中存在的任何数字或破折号,请尝试以下操作:
Regex.Match(input, @"^[\d-]+$");
^Start of string
^字符串的开始
[\d-]+one or more digits or dashes
[\d-]+一位或多位数字或破折号
$End of string
$字符串结束
回答by Manas
Any of the following Regex will work fine.
以下任何正则表达式都可以正常工作。
[0-9\-]+ ( + one or more occurance)
[\d\-]+ (as \d represents numbers)
if you want - must be between digits
如果你愿意 - 必须在数字之间
[\d]+\-*[\d]+ will match any of following
90909900
9090-9009
900--900
if you want use only one - or no - between digits, then
如果您只想在数字之间使用一个或不使用,那么
[\d]+\-?[\d]+ will match any of following
90909900 pass
9090-9009 pass
900--900 fail
回答by Salty
If that's an array of strings, consider to get it done with LINQ?
如果这是一个字符串数组,考虑用 LINQ 来完成它吗?
if (arrInput.Any(s => (!Regex.IsMatch(s, @"^[\d-]+$")))){ //OK }

