Search code examples
regexregex-lookaroundsregex-negationregex-groupregex-greedy

RegEx for quantifying and finding a character


Considering a string with 12 characters, I want to split the string in three groups of four characters and find a character in group 1 and 3.

For example:

AAAABBBBAAAA  -> B not found (they are in group 2)
ABAABBBBAAAA  -> B found in the first 4 characters (group 1)
AAAABBBBABAA  -> B found in the last 4 characteres (group 2)

I only managed to create group 1 and 3, but I don't know how to find the 'B' on them:

(^.{0,4})|(.{0,4}$)

Thanks


Solution

  • If quantifiers with an infinite width or a predetermined range are are supported in a lookbehind like in for example .NET, Python PyPi regex module or Java you might also use:

    (?<=^[AB]{0,3})B|B(?=[AB]{0,3}$)
    

    Regex example in C#

    Explanation

    • (?<=^[AB]{0,3}) Assert what is on the left is start of string, 0-3 times A or B
    • B Match literally
    • | Or
    • B Match literally
    • (?=[AB]{0,3}$) Assert what is on the right is 0-3 times A or B, assert end of string