Edit:
I have the following:
T1_sometext, T1_sometext2, T1_sometext3, T2_anothertext, T2_anothertext2, T2_anothertext3
I want to to capture each T group (followed by the same number). For example, I want to extract 2 groups in this example:
Desired outcome:
Group 1: T1_sometext, T1_sometext2, T1_sometext3
Group 2: T2_anothertext, T2_anothertext2, T2_anothertext3
I want the regex to work for unlimited numbers not just T1 and T2 (But if the number after T is the same, it should be in the same match)
CodePudding user response:
We can try using the following regex pattern:
/(T\d )_\w (?:,\s*\1_\w )*/gm
Explanation:
(T\d )
match AND captureT
followed by a number_
match underscore\w
match a word(?:,\s*\1_\w )*
optional comma/whitespace,T
followed by number,_
, and word, zero or more times
Here is a demo.
CodePudding user response:
One Simple Case
If you know in advance the number of Ti
, say N=3, then can build a regex at run time:
(T1_[\w] )|(T2_[\w] )|(T3_[\w] )
Code: regex101.