i've search many answer to match ABAB pattern
that match arbitrary character sort of 1212 or 2323, have read this too but i found that the pattern to match ABAB pattern not work, it also match 4444
i try to figure out the pattern to match such subject below:
2323
4545
9898
but may not match 4444 or 5555 because that is not in ABAB pattern, i name it AAAA pattern
can someone give me clue
thanks
You can use this pattern:
(\d)(?!\1)(\d)\1\2
(\d)
- capture the first digit to group $1
.(?!\1)
- check that the second digit is not the first digit.(\d)
- capture the second digit to group $2
.\1
- match the third digit if it is the same as the first.\2
- match the fourth digit if it is the same as the second.Working example: http://www.regex101.com/r/aV2uG1
This is a relatively confusing regular expression, and the task can be easily solved by a few lines of code. I'm not big on PHP, but this seems to work:
$s = '1112';
$valid = (strlen($s) === 4) && ($s[0] === $s[2]) && ($s[1] === $s[3]) &&
($s[0] !== $s[1]);
A simpler and more general regex pattern you can use for the ABAB pattern is
(.+)(.+)\1\2
Breakdown:
(.+)
- Match one or more characters and store in capture group 1
(.+)
- Match one or more characters and store in capture group 2
\1
- Match same item in capture group 1
\2
- Match same item in capture group 2
Working example: https://regex101.com/r/qJ2wM7/1