Search code examples
javastringreplacereplaceall

Why replaceAll("$","") is not working although replace("$","") works just fine?


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;
 }
}

Input: 2 or$ hodor or$ arya

Output: 1 0

In this program i am scanning two parameters(String) in which first one is pattern and second one is text in which i have to find pattern. Method should return 1 if pattern matched else return 0. While using replace it is working fine but when i replace replace() to replaceAll() it is not working properly as expected. How can i make replaceAll() work in this program.


Solution

  • $ is a scpecial character in regex (EOL). You have to escape it

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