haroldmoma
haroldmoma

Reputation: 135

finding pattern between two "CERRADO}" strings using negative look-ahead

I have a text file containing lines like these:

CERRADO}165856}TICKET}DESCRIPTION}some random text here\r\n
other random text here}158277747\r\n
CERRADO}165856}TICKET}FR2CODE}more random text also here}1587269339\r\n

My ultimate goal is to concatenate those lines not beginnning with "CERRADO}" string with their preceding line. There might be an arbitrary number of lines not beginning with that string on the file. This is the end result:

CERRADO}165856}TICKET}DESCRIPTION}some random text here other random text here}158277747\r\n
CERRADO}165856}TICKET}FR2CODE}more random text also here}1587269339\r\n

My first attempt was to create a simple regex to match those lines.

CERRADO\}.+\r\n(?!CERRADO\})(.+\r\n)+

After having that regex right, to create a matching group and replace it getting rid of the \r\n patterns, here is what I have so far:

The proposed regex matches all the lines in the file and not just the wanted ones.

Any ideas would be appreciated

Upvotes: 1

Views: 25

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627335

You may use

\R(?!CERRADO\})

and replace with a space.

The regex matches:

  • \R - a line break sequence that is...
  • (?!CERRADO\}) - not followed with CERRADO}.

Or,

^(CERRADO\}.*)\R(?!CERRADO\})

and replace with \1 . This regex matches:

  • ^ - start of a line
  • (CERRADO\}.*) - Capturing group 1 (later referred to with \1 backreference from the replacement pattern): CERRADO} substring and then the rest of the line
  • \R - a line break sequence
  • (?!CERRADO\}) - not followed with CERRADO}.

To make multiple replacements with this one, you will need to hit Replace All several times.

enter image description here

Upvotes: 1

Related Questions