有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

正则表达式Java字符串ReplaceAll和ReplaceFirst在替换文本处的$Symbol处失败

我写了这段代码:

public static void main(String args[]) throws Exception {
    String template = "The user has spent amount in a day";
    String pattern = "amount";
    String output = template.replaceAll(pattern, "$ 100");
    System.out.println(output);
}

这是我运行它时发生的情况:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
        at java.util.regex.Matcher.appendReplacement(Matcher.java:713)
        at java.util.regex.Matcher.replaceAll(Matcher.java:813)
        at java.lang.String.replaceAll(String.java:2190)
        at demo.BugDemo.main(BugDemo.java:16)
Java Result: 1

我正在从文件中读取数据。我应该转义文件数据中的所有$符号,还是这是一个不必要的过程?是否有其他类或库来处理这种情况

在替换文本(而不是正则表达式)中使用特殊符号有什么问题

注:

  • 我不想检查每个角色来逃避。这就是我问这个问题的原因

  • 我正在使用Java6


共 (5) 个答案

  1. # 1 楼答案

    特殊字符$的处理方法很简单。 检查下面的例子

    public static void main(String args[]){
            String test ="Other company in $ city ";
            String test2 ="This is test company ";
            try{
                test2= test2.replaceFirst(java.util.regex.Pattern.quote("test"),  Matcher.quoteReplacement(test));
                System.out.println(test2);
                test2= test2.replaceAll(java.util.regex.Pattern.quote("test"),  Matcher.quoteReplacement(test));
                System.out.println(test2);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    

    输出:

    This is Other company in $ city  company 
    This is Other company in $ city  company 
    
  2. # 2 楼答案

    $用于指定替换组的符号。你需要逃离它:

    String output = template.replaceAll(pattern, "\\$ 100");
    
  3. # 3 楼答案

    ^{}将正则表达式匹配模式作为其第一个参数,正则表达式替换模式作为其第二个参数,$在正则表达式中具有特定的含义(在匹配模式和替换模式中,尽管意义不同)

    只要用^{}来代替,我怀疑你所有的问题都会消失。只有在真正希望通过正则表达式匹配/替换时才应该使用^{我认为在这种情况下不会这样做

    编辑:关于你的问题:

    What is the problem with having a special symbol in the replacement text (not in the regex)?

    同样,关于replaceAll的文档清楚地说明了这一点:

    Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

    因此,如果您想将匹配模式视为正则表达式,而不是替换,那么使用Matcher.quoteReplacement

  4. # 4 楼答案

    试试这个

     String template = "The user has spent amount in a day";
     String pattern = "amount";
     String output = template.replaceAll(pattern, "\\$ 100");
     System.out.println(output);
    
  5. # 5 楼答案

    在替换字符串中,$是一个特殊字符:用于从要替换的模式中获取匹配的组。你可以阅读更多关于它的内容

    要解决这个问题,您可以引用替换字符串来删除$字符中的所有特殊含义:

    import java.util.regex.Matcher;
    // ...
    String output = template.replaceAll(pattern, Matcher.quoteReplacement("$ 100"));