【问题标题】:Replace All string with Regex in the replacement string? [duplicate]在替换字符串中用正则表达式替换所有字符串? [复制]
【发布时间】:2019-09-04 07:25:17
【问题描述】:

这是正文

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

我可以通过上面的代码找到我想要的东西,但是替换不起作用。

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

【问题讨论】:

  • 您的替换有什么问题?它会抛出错误吗? (如果是,请edit 问题并添加堆栈跟踪。)它会产生一些意想不到的结果吗? (如果是,请edit 问题并添加您的预期和实际输出)。它是别的东西吗? edit这个问题,不要让我猜出什么问题。

标签: java regex


【解决方案1】:

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

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

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

【讨论】:

  • 使用group()group(0) 获得完整匹配。
【解决方案2】:

您可以尝试的另一种选择是使用正则表达式环顾四周。

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

正则表达式解释:

[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

【讨论】:

    猜你喜欢
    • 2012-04-26
    • 2018-07-13
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多