Page 1 of 1

XY Regex - how to remove commas not between parens

Posted: 24 Feb 2025 04:18
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

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

Posted: 24 Feb 2025 06:17
by highend
Negative lookahead: ,(?![^()]*\))

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

Posted: 24 Feb 2025 18:20
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!