Home > Net >  python regex for a letter must be surrounded by a another letter
python regex for a letter must be surrounded by a another letter

Time:02-10

I'm trying to write a regex that only matches a string that includes lowercase a & b such that each a has the letter b immediately before it and after it.

e.g., the Regex should match the string 'bbbabbababbbbab' but not 'abbbbaabbab'

I have written an expression that does satisfy the example however, the regex should also match a string such as 'bab' but it does not.

My current expression is ^[b] (ab) [ab]*[b]$

Anyone have any advice on what I'm doing wrong?

CodePudding user response:

You are repeating single chars ab in the group (ab)

You can repeat the a's and the b's as well:

^b (?:a b )*$

Regex demo

If you only want to match a single a and the a should be there at least once:

^b (?:ab ) $

Regex demo

  • Related