XY Regex - how to remove commas not between parens

Please check the FAQ (https://www.xyplorer.com/faq.php) before posting a question...
Post Reply
Malarki
Posts: 208
Joined: 03 Dec 2019 02:51
Location: Windows 10 x64; 100% Scaling

XY Regex - how to remove commas not between parens

Post by Malarki »

I want a way to remove all commas "," from a filename except those that appear within parentheses.

Example string:
text1 text2, text3 (text4, text5) text6, [text7]
Desired string:
text1 text2 text3 (text4, text5) text6 [text7]

It can be taken as a given that all parens will occur in pairs, and won't be nested; and the commas won't appear as the first or last character, so no special cases like that.

I'm pretty sure that I can do this by disassembling the original string into sections that are either inside or outside of parentheses. Then remove commas from the latter; then reassemble the string via concatenation.

However... "Match all commas not within parentheses" sounds like it could be done in one regex. But I can't begin to see how, especially in the fairly basic flavor of regex in XY eg. no support for "If-then". Nobody has asked exactly this in StackOverflow or Reddit, it seems.

Any ideas for a direct regex approach? I don't want anyone to spend much time on this since as mentioned I can probably brute-force it; but maybe someone who thinks in regex will have a quick insight - which might only be "no way!".

Thanks

highend
Posts: 14571
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Re: XY Regex - how to remove commas not between parens

Post by highend »

Negative lookahead: ,(?![^()]*\))
One of my scripts helped you out? Please donate via Paypal

Malarki
Posts: 208
Joined: 03 Dec 2019 02:51
Location: Windows 10 x64; 100% Scaling

Re: XY Regex - how to remove commas not between parens

Post by Malarki »

That's it. Now in regex replace I can use eg.

Code: Select all

,(?![^()]*\)) > 
to remove all the commas not with parentheses.

The elegant solution I had hoped for - Thanks!

Post Reply