java - 为什么 replaceAll ("$","") 不起作用,尽管 replace ("$","") 工作得很好?

标签 java string replace replaceall

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 时它工作正常但是当我将 replace() 替换为 replaceAll() 时它无法按预期正常工作。 我怎样才能使 replaceAll() 在此程序中工作。

最佳答案

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

public String replaceAll(String regex,
                         String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

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

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

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

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

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

关于java - 为什么 replaceAll ("$","") 不起作用,尽管 replace ("$","") 工作得很好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39033719/

相关文章:

java - 编译错误 : No source code is available for type com. google.gson.Gson

c - char 字符串中的 ascii 代码

string - 我如何从 python 中的一组单词中寻找最短的唯一子序列?

bash - Vim - 在搜索时捕获字符串并在替换时使用

java:在流中搜索和替换

java - 如何从我的服务层内部创建一个 cookie 并添加到 http 响应?

java - JGraphX 移动单元并保持边缘

linux - 无法在 LINUX 的 C++ 中将 STRING 转换为 INT

mysql - 将数字的中间值更改为 "xxxx"

java - 如何读取标记 x 和 y