简体   繁体   中英

Java string replaceAll method

hi i want to use Java string replaceAll() method to replace "x3" with "multiplied by 3" in my text file. But there is a string occurence "xxx3" which i do not want to replace. how can I do it

Example :

        ACTUAL                                     DESIRED  
1)ENGAGE XX3 COLOGNE 165ML          ENGAGE XX3 COLOGNE 165ML
2)FDW MEN REFRESHING PULSE 125GMSX3   FDW MEN REFRESHING PULSE 125GMS multuiplied by 3

Try

StringName.replaceAll("(?<!x)x3", "multiplied by 3");

replaceAll method uses a regex as first argument, this pattern has two parts :

"x3" : each time the method finds "x3" in your string, there is a chance to match the pattern

"(?<!x)" is a negative lookbehind. That means : "If my current part of the string is precedeed by x, the pattern will not match, else it will"

eg : "(?<!example)x3" will match each "x3" in your string, except any "examplex3"

Hope it helped you

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