Is there a short regular expression that has the same effect as (0 | 1) * (1100 | 1010 | 1001 | 0110 | 0101 | 0011)?

Basically, I want to write a regex to represent any string {0, 1} whose last 4 characters have an equal number of 0 and 1. Of course,

(0 | 1) * (1100 | 1010 | one thousand | 0110 | 0101 | 0011)

will do the trick, but if there is a more concise way?

+4
source share
1 answer

This regex will do the trick.

^[01]*(?=.*?1.*1)(?=.*?0.*0).{4}$

Demo

^ It is claimed that we are at the beginning.

[01]* Matches 0 or 1, zero or more times.

lookahead (?=.*?1.*1)(?=.*?0.*0).{4}$ , 4 1 0. , . , @nhahdth.

^[01]*(?=.{4}$)(?=.*?0.*0).*?1.*1.*

DEMO

+5

All Articles