簡體   English   中英

Java正則表達式用特定的字符串替換輸入中的幾個組

[英]java regex to replace few groups in input with particular string

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中是否可以使用正則表達式將輸入字符串替換為捕獲組的特定值。

請幫忙

String類的replacereplaceAll方法是執行此操作的最佳方法。 它們支持正則表達式字符串作為搜索參數。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM