简体   繁体   中英

How to avoid replacing specific words in a text in java

I have a method like this :

for(String abc:abcs){  
   xyz = abc.replaceAll(abc+"\\(", "_"+abc+"\\(");
}

How to avoid replacing few replacements which have specific prefixes for them in java

I tried this :

String data = "Today, abc.xyz is object oriented language";
String regex = "(?<!abc.)xyz";     
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(data);
System.out.println(matcher.find());

Does this work for you?

package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        String prefix = "abc";
        String replaceWith = " text";
        String input = "This xyz is an example xyz to show how you can replace certains values of the xyz.\n"
                + "The xyz can conain any arbitrary xyz, for example abc.xyz.";
        Pattern pattern = Pattern.compile("[^" + prefix + "].xyz");
        Matcher m = pattern.matcher(input);
        while (m.find()) {
            input = input.replace(m.group().substring(1), replaceWith);
        }
        System.out.println(input);
    }
}

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