【问题标题】:Unable to replace a string with another string in java using regex无法使用正则表达式在java中用另一个字符串替换一个字符串
【发布时间】:2022-12-20 00:01:35
【问题描述】:

我有一个字符串,想替换其中的某些字符。 输入String = "abc test=0 test1=123 test2=764" 输出String = "abc test=$test test1=$test1 test2=$test2"

我在 java 中使用 replace 和 replaceAll 尝试了一些事情。 例如 :

String abc = directiveValue.replaceAll("test%", test+"=$"+test);

要么

String abc = directiveValue.replaceAll("test[.*]", test+"=$"+test);

【问题讨论】:

    标签: java regex


    【解决方案1】:

    我们可以使用正则表达式替换:

    String input = "abc test=0 test1=123 test2=764";
    String output = input.replaceAll("(\w+)=\w+", "$1=\$$1");
    System.out.println(output);
    
    // abc test=$test test1=$test1 test2=$test2
    

    【讨论】:

      【解决方案2】:

      你可以匹配:

      (testd*=)S*
      

      Regex demo

      并替换为 2 个捕获组之间的美元符号 $1$$1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-08
        • 2016-11-24
        相关资源
        最近更新 更多