Home > Enterprise >  Can you match a single character only that's within parenthesis for replacement using regex?
Can you match a single character only that's within parenthesis for replacement using regex?

Time:10-19

I have a weird case where the only real tool I have to use is Notepad without some heavy lifting, and I have a | delimited text file that has |s in the text that I need to remove.

Each | that I need to remove falls within parenthesis, so the text patterns look like this:

(123 | 456) (11.1 | 11.2)

...and so on.

My ideal result would be removing the |s contained within ()s and replacing with a -, so:

(123 - 456) (11.1 - 11.2)

So far I have:

\(.*\|.*\)

That matches each set of parenthesis that contains a | reliably, but I can't figure out a way to just match the | itself for replacement. Any ideas?

CodePudding user response:

With your shown samples, please try following regex in notepad

find what: ([^|]*)\|([^)]*\))

Replace with: $1-$2

enter image description here

If you have multiple pipes (like in (123 | 456 | 23) (11.1 | 11.2 | 788 | 6896)):

(\G(?!^)|\()([^()|]*)\|(?=[^()]*\))

But now, replace with $1$2-. See the regex demo. This is compatible with some other common text editors, hence I did not suggest using a pattern with \K (see this regex demo).

CodePudding user response:

I just tested this code, which is a bit safe to use, but a little long code ....

Find: (\(\d [. \d]*)[|](?= \d [.\d]*)
Replace All: $1-

  • Related