【问题标题】:Why replaceAll("$","") is not working although replace("$","") works just fine?为什么 replaceAll("$","") 不起作用,尽管 replace("$","") 工作得很好?
【发布时间】:2016-12-26 07:12:55
【问题描述】:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
 {
       int turns;
     Scanner scan=new Scanner(System.in);
     turns=scan.nextInt();
     while(turns-->0)
     {
       String pattern=scan.next();
       String text=scan.next();
       System.out.println(regex(pattern,text));

      }
 }//end of main method
 static int regex(String pattern,String text)
 {
     if(pattern.startsWith("^"))
       {
           if(text.startsWith(pattern.replace("^","")))
           return 1;
       }
       else if(pattern.endsWith("$"))
       {
           if(text.endsWith(pattern.replace("$","")))
           return 1;
       }
       else
       {
          if(text.contains(pattern))
          return 1; 
       }
       return 0;
 }
}

输入: 2 或$ 阿多 或$ 亚亚

输出: 1 0

在这个程序中,我正在扫描两个参数(字符串),其中第一个是模式,第二个是我必须在其中找到模式的文本。如果模式匹配,则方法应返回 1,否则返回 0。 使用替换时它工作正常,但是当我将 replace() 替换为 replaceAll() 时,它无法按预期正常工作。 我怎样才能让 replaceAll() 在这个程序中工作。

【问题讨论】:

标签: java string replace replaceall


【解决方案1】:

因为replaceAll 需要一个定义正则表达式 的字符串,而$ 在正则表达式中表示“行尾”。从链接:

public String replaceAll(String regex,
                         String replacement)

用给定的替换替换此字符串中与给定正则表达式匹配的每个子字符串。

您需要使用反斜杠对其进行转义(在字符串文字中也必须对其进行转义):

if(text.endsWith(pattern.replaceAll("\\$","")))

对于要逐字替换的复杂字符串,Pattern.quote 很有用:

if(text.endsWith(pattern.replaceAll(Pattern.quote("$"),"")))

您在这里不需要它,因为您的替换是 "",但如果您的替换可能包含特殊字符(如反斜杠或美元符号),请在替换字符串上也使用 Matcher.quoteReplacement

【讨论】:

  • @OldCurmudgeon 在替换部分Matcher,quoteReplacement() 因为$\ 在那里也很特殊($x 可以访问来自x\ 组的匹配,所以我们可以逃脱$).
  • @OldCurmudgeon:啊,是的,谢谢,Java 实际上有这个有用的方法。我一直在等待 TC-39 将其添加到 JavaScript。 :-|
【解决方案2】:

$ 是正则表达式 (EOL) 中的特殊字符。你必须逃避它

pattern.replaceAll("\\$","")

【讨论】:

    【解决方案3】:

    尽管名称相似,但这是两种截然不同的方法。

    replace 用其他子字符串 (*) 替换子字符串。

    replaceAll 使用正则表达式匹配,$ 是一个特殊的控制字符(意思是“字符串/行的结尾”)。

    你不应该在这里使用replaceAll,但如果你必须,你必须quote the $

     pattern.replaceAll(Pattern.quote("$"),"")
    

    (*) 让事情变得更加混乱,replace 也替换了 all 的出现,因此方法名称的唯一区别并不能全部描述功能的区别。

    【讨论】:

      【解决方案4】:

      通过将 $ 替换为 \$ 来引入另一个级别的复杂性。

      "$ABC$AB".replaceAll(Matcher.quoteReplacement("$"), Matcher.quoteReplacement("\\\\$"))
      // Output - \\$ABC\\$AB
      

      这对我有用。

      对于此处报告的问题,

      "$ABC$AB".replaceAll(Matcher.quoteReplacement("$"), "")
      

      应该可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        相关资源
        最近更新 更多