简体   繁体   中英

Regex to match only 1 digit between 0 to 2

I'm trying to write a regex that will have thoese properies:

  • Only one digit. (no more, no less)
  • The digit can only be 0 or 1 or 2.

The second property is easy (0|1|2) or [0-2] , but I cant limit it to one digit.

Thank you.

In .NET (as well as plenty of other regex implementations), the methods to for regex matching don't check whether the complete string matches, they check whether any substring matches. By its logic, "awffowhf35lhns1afwa" is a match, because it contains a substring "1" .

To only allow whole string matches, you can use the ^ and $ special characters to require positioning at the beginning and the end of a string: ^[0-2]$ .

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