简体   繁体   English

正则表达式:非零数字,后跟一个或多个空格,后跟非零数字

[英]Regex: non-zero number followed by one or more spaces followed by non-zero number

Trying to match a user input in the format [1-9], whitespace, [1-9] 尝试匹配格式为[1-9],空格,[1-9]的用户输入
So 所以
1 1 should pass 1 1应该通过
1 0 should fail 1 0应该失败

new Regex(@"^[1-9]+\s+\d+").IsMatch(input) //works but allows 0 for the 2nd number
new Regex(@"^[1-9]+\s+\[1-9]+").IsMatch(input) //does not work for some reason

I feel like I'm missing something super basic, but I can't find the answer. 我觉得我缺少一些超级基础知识,但找不到答案。

Both your regexps do not work as intended. 您的两个正则表达式均无法正常工作。 The ^[1-9]+\\s+\\d+ pattern matches 1+ digits from 1 to 9 , then 1+ whitespaces, and then any 1+ digits that can be followed with anything, any number of any chars. ^[1-9]+\\s+\\d+模式匹配从19 1+个数字,然后匹配1+个空格,然后匹配可以随便跟随的任意1+个数字,任意数量的任何字符。 The ^[1-9]+\\s+\\[1-9]+ pattern contains an escaped [ and instead of matching any 1+ digits from 1 to 9 with [1-9] your \\[1-9]+ matches a [ , then 1-9 substring and then 1+ ] chars. ^[1-9]+\\s+\\[1-9]+模式包含转义的[ ,而不是将19任何1+数字与[1-9]匹配,您的\\[1-9]+[ ,然后是1-9子字符串,然后是1+ ]字符。

If you plan to match strings consisting of single non-zero digits separated with 1+ whitespaces, use @"^[1-9]\\s+[1-9]$" . 如果计划匹配由单个非零数字组成的字符串,这些数字由1+空格分隔,则使用@"^[1-9]\\s+[1-9]$" See this regex demo . 请参阅此正则表达式演示

If you plan to match a string that consists of two digit chunks not starting with 0 and separated with 1 or more whitespace chars, use 如果您计划匹配一个字符串,该字符串包含两个不以0开头且以1个或多个空格字符分隔的数字块,请使用

@"^[1-9][0-9]*\s+[1-9][0-9]*$"

See the regex demo . 参见regex演示 Note that $ is an end of string anchor that does not allow almost any chars after it (it does allow an \\n at the end of the string, so, you might want to use \\z instead of $ ). 请注意, $是字符串锚的结尾,它后面几乎不允许包含任何字符(它的确允许在字符串末尾使用\\n ,因此,您可能要使用\\z而不是$ )。

Pattern details 图案细节

  • ^ - start of string ^ -字符串的开头
  • [1-9] - a 1 , 2 ... 9 [1-9] -一个12 ... 9
  • [0-9]* - zero or more digtis [0-9]* -零个或多个数字
  • \\s+ - 1+ whitespace chars \\s+ -1+空格字符
  • [1-9][0-9]* - see above [1-9][0-9]* -参见上文
  • $ / \\z - end of string / the very end of string anchors. $ / \\z字符串结尾/字符串锚点的结尾。

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

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