0
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中是否可以使用正则表达式将输入字符串替换为捕获组的特定值。

请帮忙

4

2 回答 2

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);
于 2013-11-06T11:31:00.030 回答
0

String 类replacereplaceAll方法是最好的方法。它们支持正则表达式字符串作为搜索参数。

于 2013-11-06T10:58:44.050 回答