简体   繁体   中英

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]
So
1 1 should pass
1 0 should fail

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

If you plan to match strings consisting of single non-zero digits separated with 1+ whitespaces, use @"^[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

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

See the regex demo . 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 $ ).

Pattern details

  • ^ - start of string
  • [1-9] - a 1 , 2 ... 9
  • [0-9]* - zero or more digtis
  • \\s+ - 1+ whitespace chars
  • [1-9][0-9]* - see above
  • $ / \\z - end of string / the very end of string anchors.

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