Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific characters inside parentheses using regex

I have a line like this:

BlockedMatch(XA, YB), Correlation(XA, QC), Correlation(YB, QC), Correlation(QC, YB)

I want it to look like this:

BlockedMatch(XAYB), Correlation(XAQC), Correlation(YBQC), Correlation(QCYB)

I can't just do a replace on ", " because it will remove those instances that exist outside of the parentheses.

I tried this:

replaceAll("\\((.*?)\\)", "")

which replaces everything inside the parentheses (not just the comma). I've tried to add just the comma and space combination into that regex, but it doesn't seem to remove anything then.

Could someone show me how to specify to only remove the ", " (comma-space) when it occurs inside parentheses?

like image 411
AHungerArtist Avatar asked Jul 11 '26 14:07

AHungerArtist


2 Answers

Use a look ahead:

str = str.replaceAll(", (?=[^(]*\\))", "");

This regex says "replace the comma-space only when the next bracket character is a close bracket"


Some test code:

String str = "BlockedMatch(XA, YB), Correlation(XA, QC), Correlation(YB, QC), Correlation(QC, YB)";
str = str.replaceAll(", (?=[^(]*\\))", "");
System.out.println(str);

Output:

BlockedMatch(XAYB), Correlation(XAQC), Correlation(YBQC), Correlation(QCYB)
like image 108
Bohemian Avatar answered Jul 14 '26 04:07

Bohemian


The safest way to do this is to use two regexes: First, capture all (...) and from those results, remove all commas and optional whitespace.

For your specific case, you can search , *([^()]*)(?=\)) and replace with \1 which you can see here.

This may have issues with edge cases where you have multiple things within your parentheses that you wish to remove (such as (XA, YB, ZC)).

Or (without replacing) search for , *(?=[^(]*\)) and replace with (nothing) which you can see here. This handles multiple , fairly well, but will have problems if you have embedded (...) characters.

like image 40
OnlineCop Avatar answered Jul 14 '26 02:07

OnlineCop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!