简体   繁体   中英

ReplaceAll String java regex

I have a string that contains the following:

"Hello my name is (0.9%) and (15%) bye (10.5%) also (C9, B6)"

I want to replaceAll so I get rid of the brackets containing percentages but not the other numbers like so:

"Hello my name is and bye also C9, B6"

Currently I have this but it removes all my numbers, Any idea how I could fix it:

.replaceAll("[\\([0-9]\\%)]","");

Something like this maybe?

"Hello my name is (0.9%) and (15%) bye (10.5%) also (C9, B6)".replaceAll("\\((?:\\d|\\.)+%\\)", "")

Demo

This here also deletes a single whitespace after each parenthesized percentage:

"Hello my name is (0.9%) and (15%) bye (10.5%) also (C9, B6)".replaceAll("\\((?:\\d|\\.)+%\\) ", "")

Gives:

Hello my name is and bye also (C9, B6)

Remove the outer brackets and add matching to digits before and after an optional dot.

.replaceAll("\\([0-9]+?\\.?[0-9]+?\\%\\)", "");

Note: You can change the "+" to "*" if you want to allow a leading or trailing dot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM