简体   繁体   中英

Regular expression - number without same digit beside

I'm looking for a regex, which fits to every number, that is made from 0,1,2 and don't have the same digits beside - 02021 fits, 0122 doesn't fit. How it can be written?

You can start with a digit between zero and two. Capture that in a group and check that the following is not the captured value. Capture that in a non capturing group and repeat that.

^(?:([0-2])(?!\\1))*$

Explanation

  • From the beginning of the string ^
  • A non capturing group (?:
  • A capturing group (
  • A character range from 0 till 2 [0-2]
  • Close capturing group )
  • A negative lookahead (?!
  • Assert that what is following is not equal to the first capturing group
  • Close the negative lookahead )
  • Close the non capturing group )
  • Repeat the non capturing group zero or more times *
  • The end of the string $

You can use the following regex:

^(([012])(?!\2))+$

tested here: https://regex101.com/r/6vevDl/1

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