用替换字符串中的Regex替换所有字符串?

时间:2019-09-03 22:46:53

标签: java regex

这是文字

<some string here could contain W or L letter><W1>123<W2>123<W3>123. 

我希望替换

<W(number)> 

模式

<L(number)>

模式。

String str = "<WLWLWL><W1><FS>123<W2><FS>345<E>";
    System.out.println(str);

    Pattern p = Pattern.compile("<[A-Z]\\d>");
    Matcher m = p.matcher(str);

    while(m.find()){
        System.out.println(m.group());
    }

    str.replaceAll("<[A-Z]\\d>", "<L\\d>");
    System.out.println(str);

我可以在上面的代码中找到我想要的,但是替换无法正常工作。

我想替换字符串不包含正则表达式。那么最好的方法是什么?

2 个答案:

答案 0 :(得分:3)

我认为您正在寻找一个捕获小组:

str = str.replaceAll("<[A-Z](\\d)>", "<L$1>");

请注意开头的作业。 replaceAll()不会修改字符串(字符串是不可变的);它会返回一个新的。

答案 1 :(得分:1)

您可以尝试的另一种替代方法是使用正则表达式环顾四周。

str = str.replaceAll("[a-zA-Z](?=\\d)", "L");

RegEx说明:

[a-zA-Z](?=\\d)    finds the letter within (a-zA-Z) which has a number after it

输出:

<WLWLWL><L1><FS>123<L2><FS>345<E>

来源:Regex lookahead, lookbehind and atomic groups

有关RegEx模式的更多信息:Class Pattern

replaceAll():

此外,replaceAll()确实修改了您作为参数传递的字符串,但由于字符串是不可变的,因此该函数返回一个新的字符串。来自String Java

public String replaceAll(String regex, String replacement)
Returns:
   The resulting String