If you want to only perform one search of s
, you can either do your own indexOf()
loop, or use a regular expression replacement loop.
Here is an example of using a regular expression replacement loop, which uses the appendReplacement()
and appendTail()
methods to build the result.
To eliminate the need for doing a string comparison to figure out which keyword was found, each keyword is made a capturing group, so existence of keyword can be quickly checked using start(int group)
.
String s = "This %ToolBar% is a %Content%";
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("%(?:(ToolBar)|(Content))%").matcher(s);
while (m.find()) {
if (m.start(1) != -1)
m.appendReplacement(buf, "Edit ToolBar");
else if (m.start(2) != -1)
m.appendReplacement(buf, "made by Paul");
}
m.appendTail(buf);
System.out.println(buf.toString()); // prints: This Edit ToolBar is a made by Paul
The above runs in Java 1.4 and later. In Java 9+, you can use StringBuilder
instead of StringBuffer
, or you can do it with a lambda expression using replaceAll()
:
String s = "This %ToolBar% is a %Content%";
String result = Pattern.compile("%(?:(ToolBar)|(Content))%").matcher(s)
.replaceAll(m -> (m.start(1) != -1 ? "Edit ToolBar" : "made by Paul"));
System.out.println(result); // prints: This Edit ToolBar is a made by Paul
A more dynamic version can be seen in this other answer.