Home > Software design >  How do I use a regular expression to match any string have at least 3 B's and at most 2 A'
How do I use a regular expression to match any string have at least 3 B's and at most 2 A'

Time:06-11

I am not a regex expert, but my request is simple: I need to match any string that has at least 3 characters of B and at most 2 characters of A

so for example:

"ABABBB" => Accepted
"ABBBBBB" => Accepted
"BBB"     => Accepted
"ABB"     => Rejected
"AABB"    => Rejected
"AA"      => Rejected

CodePudding user response:

I would express your requirement as:

^(?![AB]*A[AB]*A[AB]*A)[AB]*B[AB]*B[AB]*B[AB]*$

This pattern says to:

^                            from the start of the string
    (?![AB]*A[AB]*A[AB]*A)   ensure that three (or more) A's do NOT occur
    [AB]*B[AB]*B[AB]*B[AB]*  then match any A-B string with three or more B's
$                            end of the string

Here is a working demo.

CodePudding user response:

You can use this

(?=^(?:.*B){3,}.*$)(?=^(?:[^A]*A){0,2}[^A]*$).*

Regex Explanation

  • (?= Lookahead assertion - assert that the following regex matches
    • ^ Start of a string
    • (?: Non-capturing group
      • .*B Match anything and B
    • ) Close non-capturing group
    • {3,} Not less than 3 repetitions
    • .*$ Match anything till the end of the string
  • ) Close lookahead
  • (?= Lookahead assertion - assert that the following regex matches
    • ^ Start of a string
    • (?: Non-capturing group
      • [^A]* Match anything except A
      • A Match A
    • ) Close non-capturing group
    • {0,2} Matches the previous regex from 0 to 2 times
    • [^A]*$ Match anything except A till the end of the string
  • ) Close lookahead
  • .* Match the whole string if the previous lookarounds both matched

Summary

Match all (.*) that contains at least 3 B ((?=^(?:.*B){3,}.*$)) and at most 2 A ((?=^(?:[^A]*A){0,2}[^A]*$))

Also, see regex demo

  • Related