Regex c# obtain subgroup of a captured group

Viewed 89

It seems a simple question, but I don't think it is so easy.

From the example string AAACARACBBBBBDZAAAAEE, I want to extract the first 8 characters (= AAACARAC) and from this resulting 8-char long string, I want to extract everything except the leading 'A' characters (= CARAC).

I tried with this regex (?^[A]<WORD>\w{8}), but I dont know how to apply another regex on the captured group named WORD?

2 Answers

This is the regex you want:

(?=^.{8}(.*)$)A*(?<WORD>.*?)\1$

See a demo here (click then on "Table" for looking at the specific matches).

The regex firs will match the first eight characters looking for what comes next (matching this "tail" in the first capturing group), then will restart from the beginning of the string excluding all the trailing As and matching for as less character as possible such that these characters are followed by the same content of the first capturing group.

Using C#, you might also use a positive lookbehind to assert 8 chars to the left, matching optional A's and capture the chars that follow in a group.

^A*(?<WORD>[^\sA].*)(?<=^.{8})
  • ^ Start of string
  • A* match optional repetitions of A
  • (?<WORD> Named group WORD
    • [^\sA].* Match any non whitespace char except A
  • ) Close named group WORD
  • (?<=^.{8}) Assert 8 chars to the left of the current position

.NET regex demo

enter image description here

If you only want to match word characters:

^A*(?<WORD>[^\WA]\w*)(?<=^\w{8})

.NET Regex demo

Related