Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression: Match a string that contains no more than three consecutive Bs (without using negative lookahead)

Tags:

regex

This is a simple question but I just recently started learning about regex.

I need to give a regex that describes all strings that contain no more than three consecutive Bs.

It should match:

sdBBdfsBBB

BfsBBBdsfBBB

It shouldn't match:

fsBBBBsfBB

BBBBBfsBBBsd

I am not allowed to use negative lookahead, only fundamental operations and shortcuts and I have no idea how to solve this... I know that the regex .*B{1,3}.* would match the strings that I want my regex to match but it would also match those I do not want my regex to match...

like image 711
bananasananas Avatar asked Jan 20 '26 05:01

bananasananas


1 Answers

To not match empty strings, you could match either repeated sets of 1-3 times a B with at least any char except a B in between or match a string that ends with 1-3 times a B

^(?:[^B]*(?:B{1,3}[^B]+)+B{0,3}|[^B]*B{1,3})$
  • ^ Start of string
  • (?: Non capture group
    • [^B]* Match 0+ times any char except B
    • (?: Non capture group
      • B{1,3}[^B]+ Repeat 1+ times 1-3 B's and 1+ times any char except B
    • )+ Close group and repeat 1+ times
    • B{0,3} Match 0-3 B's at the end
    • | Or
    • [^B]*B{1,3} Match 0+ times any char except B and then 1-3 times a B
  • ) Close group
  • $ End of string

Regex demo

If empty string are allowed, the pattern could be shortened to

^(?:[^B]*(?:B{1,3}[^B]+)*B{0,3})$

Regex demo

Note that negated character class [^B] matches any char except a B and could possibly also match a newline. To not allow newlines to match, use [^B\r\n] or [^B\s] to exclude whitespace chars.

like image 195
The fourth bird Avatar answered Jan 21 '26 18:01

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!