在我的 C# 代码中,我有以下内容 - 我想让它检查表达式是否只包含数字或破折号,如果我输入字母 K 和破折号或数字,它仍然会接受。如何让表达式仅为数字或破折号:
Match match = Regex.Match(input, @"[0-9-]");
请问需要翻译的内容是什么?Match match = Regex.Match(input, @"^[0-9-]*$");
^
表示匹配应该从输入的开头开始,$
表示它应该在输入的结尾结束。
*
表示只应该有0个或更多个数字或破折号(使用 +
代替1个或更多个)。
Match match = Regex.Match(input, @"^[0-9\-]$");
? - Steve B你的正则表达式匹配的是字符串中是否存在任意数字或短横线,尝试使用以下表达式:
Regex.Match(input, @"^[\d-]+$");
^
字符串开头
[\d-]+
一个或多个数字或破折号
$
字符串结尾
[0-9\-]+ ( + one or more occurance)
[\d\-]+ (as \d represents numbers)
如果您想要-必须位于数字之间
[\d]+\-*[\d]+ will match any of following
90909900
9090-9009
900--900
[\d]+\-?[\d]+ will match any of following
90909900 pass
9090-9009 pass
900--900 fail
你需要转义第二个破折号。
Match match = Regex.Match(input, @"[0-9\-]");
我承认我没有尝试过,但它应该可以工作。
这实际上只适用于一个字符。如果您想要使用多个字符,例如“123-5”,那么请将您的正则表达式更改为...
Match match = Regex.Match(input, @"[0-9\-]+");
^
和$
。 - J Manif (arrInput.Any(s => (!Regex.IsMatch(s, @"^[\d-]+$")))){ //OK }