Mari_Yaguchi
Mari_Yaguchi

Reputation: 457

How to check a string that contains more than one pattern and replace that pattern


I tried to check a string that contains some patterns, and I want to replace that pattern. I stored that pattern in an ArrayList. Here is what I've done:

public static void main(String args[]){
    ArrayList<String> pattern = new ArrayList<String>();
    pattern.add("pattern1");
    pattern.add("pattern2");
    pattern.add("pattern3");
    pattern.add("pattern4");
    pattern.add("pattern10");
    pattern.add("pattern20");

    ArrayList<String> replace = new ArrayList<String>();
    replace.add("(*pattern1*)");
    replace.add("(*pattern2*)");
    replace.add("(*pattern3*)");
    replace.add("(*pattern4*)");
    replace.add("(*pattern10*)");
    replace.add("(*pattern20*)");

    String sentence = "some sentence pattern1 and pattern10 or pattern20";

    for(int i = 0; i < pattern.size(); i++){
        if(sentence.contains(pattern.get(i))){
            sentence = sentence.replace(pattern.get(i), replace.get(i));
        }
    }
    System.out.println(sentence);
}

The code above not replace all my pattern. The result is

some sentence (*pattern1*) and (*pattern1*)0 or (*pattern2*)0

The result is not what I expected. I expect something like this

some sentence (*pattern1*) and (*pattern10*) or (*pattern20*)

Can someone help me to check the string with all the pattern and than replace the pattern?

Upvotes: 0

Views: 109

Answers (3)

Mer
Mer

Reputation: 762

Just change your for loop to this, and your program will work.

for(int i = 0; i < pattern.size(); i++){
    Pattern pat = Pattern.compile(pattern.get(i)+"(?:\\W|$)");
    Matcher m = pat.matcher(sentence);
    if(m.find()){
        sentence = sentence.replaceAll(m.group(), replace.get(i));
    }
}

Upvotes: 0

BobTheBuilder
BobTheBuilder

Reputation: 19294

You should check for pattern10 before pattern1, as pattern1 will also change pattern10...

In this solution you need to verify than no target pattern (what you replace with) contain source pattern (what you replace), otherwise some target patterns will also be changed.

Another solution is to add space at the end of each String, but then you need to (temporary) add another space at the end of the sentence.

Upvotes: 2

juanignaciosl
juanignaciosl

Reputation: 3573

You can simplify that with digit matching and grouping:

public static void main(final String args[]) {
    final String sentence = "some sentence pattern1 and pattern10 or pattern20";
    System.out.println(sentence.replaceAll("pattern([\\d]*)", "(*pattern$1*)"));
}

Upvotes: 0

Related Questions