How can I capture the same text multiple times using regex?

Viewed 202

I need to match the occurrence of a character before a string. The string might occur multiple times, meaning the character might change.

Test subject:

§aUsername: Message, which happens to contain Username. §3Wow, Username again.

I would want three groups, because Username occurs three times in the subject.

Desired output:

["Username", 'a']
["Username", 'a']
["Username", '3']

I wrote this regex, but it only works with one occurance of Username.

My (failed) attempt:

§(.).*?Username

Edit: That regex entirely ignores the second occurence of Username, which should match the same character (a) as the first one.

Its output:

["Username", 'a']
["Username", '3']
1 Answers

If a quantifier in a lookbehind is supported (.NET, Pyton PiPy module or the newer Javascript engines), you could use a capture group in the lookbehind.

The match will be Username, the group 1 will contain a single any character except a newline.

(?<=§(.)[^§]*)Username
  • (?<= Positive lookbehind, asser what is to the left is
    • §(.) Match § and capture in group 1 a single any char
    • [^§]* Match any char except §, using a negated character class, any number of times
  • ) Close lookbehind
  • Username Match literally

Regex demo

Related