Arvo Bowen
Arvo Bowen

Reputation: 4929

RegEx multiple capture groups replaced in a string

I have a string of data...

"123456712J456","D","TEST1~TEST2~TEST3~TEST4~TEST5"

I want to take the following string and make 5 strings.

"123456712J456","D","TEST1"
"123456712J456","D","TEST2"
"123456712J456","D","TEST3"
"123456712J456","D","TEST4"
"123456712J456","D","TEST5"

I currently have the following regex...

//In a program like Textpad
<FIND> "\(.\{13\}\)","D","\([^~]*\)~\(.*\)
<REPLACE> "\1","D","\2"\n"\1","D","\3

//On the regex101 site
"(.{13})","D","([^~]*)~(.*)

Now if I run this 5 times it would work fine. The problem is there is an unknown number of lines to be made. For example...

"123456712J456","D","TEST1~TEST2~TEST3~TEST4~TEST5"
"123456712J457","D","TEST1~TEST2~TEST3"
"123456712J458","D","TEST1~TEST2"
"123456712J459","D","TEST1~TEST2~TEST3~TEST4"

I was hoping to be able to use a MULTI capture group to make this work. I found this PAGE talking about the common mistake between repeating a capturing group and capturing a repeated group. I need to capture a repeated group. For some reason I just could not make mine work right though. Anyone else have an idea?


RESOURCES:

Upvotes: 0

Views: 569

Answers (2)

Alan G&#243;mez
Alan G&#243;mez

Reputation: 378

A Vim regex can achieve this:

:s/\(.\{-},\)\(.\{-},\)"\(.\{-}\)\~\(.\{-}\)\~\(.\{-}\)\~\(.\{-}\)\~\(.*\)"/\1\2"\3"\r\1\2"\4"\r\1\2"\5"\r\1\2"\6"

OUTPUT

"123456712J456","D","TEST1"
"123456712J456","D","TEST2"
"123456712J456","D","TEST3"
"123456712J456","D","TEST4"

Upvotes: 0

vks
vks

Reputation: 67968

Try this.See demo.Just club match1 and rest of the matches.

http://regex101.com/r/yR3mM3/17

RegEx:

(.*,)|([^"~]+)

Example:

"1234567123456","T","TEST1~TEST2~TEST3~TEST4~TEST5"

Results:

MATCH 1
  1.    [0-20]  `"1234567123456","T",`

MATCH 2
  2.    [21-26] `TEST1`

MATCH 3
  2.    [27-32] `TEST2`

MATCH 4
  2.    [33-38] `TEST3`

MATCH 5
  2.    [39-44] `TEST4`

MATCH 6
  2.    [45-50] `TEST5`

Upvotes: 1

Related Questions