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/