Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...