sirwittles
sirwittles

Reputation: 25

Regex replace in capture group

I have a snippet of text from EDI X12. I am trying to find lines where a BBQ segment is followed by another BBQ segment. I want to replace all BBQ segments in the second line with BBB

Orig text

HI*BBR<0Y6D0Z1<D8<20190816~
HI*BBQ<05BC0ZZ<D8<20190806*BBQ<05BB0ZZ<D8<20190729*BBQ<06UM07Z<D8<20190729~
HI*BBQ<0JBL0ZZ<D8<20190809*BBQ<0J9N0ZZ<D8<20190816*BBQ<0KBS0ZZ<D8<20190816~
HI*BI<71<RD8<20190716-20190722~

Needs to become

HI*BBR<0Y6D0Z1<D8<20190816~
HI*BBQ<05BC0ZZ<D8<20190806*BBQ<05BB0ZZ<D8<20190729*BBQ<06UM07Z<D8<20190729~
HI*BBB<0JBL0ZZ<D8<20190809*BBB<0J9N0ZZ<D8<20190816*BBB<0KBS0ZZ<D8<20190816~
HI*BI<71<RD8<20190716-20190722~

This targets what I am looking for in capturing group 3, but how to replace BBQ with BBB within that group?

(^HI\*BBQ.+?~\r\n)(^HI\*)(BBQ.+?~\r\n)

Thanks for any ideas!

Upvotes: 1

Views: 389

Answers (1)

Toto
Toto

Reputation: 91373

  • Ctrl+H
  • Find what: (?:^HI\*BBQ\b.+?~\RHI\*BB|\G(?!^).*?\bBB)\KQ\b
  • Replace with: B
  • CHECK Match case
  • CHECK Wrap around
  • CHECK Regular expression
  • UNCHECK . matches newline
  • Replace all

Explanation:

(?:         # non capture group
^           # begining of line
  HI\*BBQ   # literally
  .+?       # 1 or more any character but newline
  ~         # a tilde
  \R        # any kind of linebreak
  HI\*BB    # literally
|           # OR
  \G        # restart from last match position
  (?!^)     # not at the beginning of line
  .*?BB     # 0 or more any character but newline, not greedy, followed by BB
)           # end group
  \K        # forget all we have seen until this position
  Q         # the letter Q

Screen capture (before):

enter image description here

Screen capture (after):

enter image description here

Upvotes: 1

Related Questions