import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex {
public static void main(String args[]){
Pattern p = Pattern.compile(".*?(cat).*?(dog)?.*?(tiger)");
String input = "The cat is a tiger";
Matcher m = p.matcher(input);
StringBuffer str = new StringBuffer();
if (m.find()) {
//In the output i want to replace input string with group 3 with group 1 value and group 2 with cow. Though group2 is present or not.
//i.e. group 2 is null
}
}
}
我想知道在java中是否可以使用正则表达式替换具有捕获组的特定值的输入字符串。
请帮忙
答案 0 :(得分:0)
String类的replace
和replaceAll
方法是执行此操作的最佳方法。它们支持正则表达式字符串作为搜索参数。
答案 1 :(得分:0)
Pattern p = Pattern.compile("(cat)(.*?)(dog)?(.*?)(tiger)");
String input = "The cat is a tiger";
Matcher m = p.matcher(input);
StringBuffer str = new StringBuffer();
while(m.find())
{
m.appendReplacement(str, "$5$2$3$4$1");
}
m.appendTail(str);
System.out.println(str);
顺便说一句,如果有一只狗没关系,你可以简化它:
Pattern p = Pattern.compile("(cat)(.*?)(tiger)");
String input = "The cat is a tiger";
Matcher m = p.matcher(input);
StringBuffer str = new StringBuffer();
while(m.find())
{
m.appendReplacement(str, "$3$2$1");
}
m.appendTail(str);