Why replaceAll(“$”,“”) is not working although replace(“$”,“”) works just fine? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Why replaceAll(“$”,“”) is not working although replace(“$”,“”) works just fine? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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

pattern.replaceAll("$","")
We are here to answer your question about Why replaceAll(“$”,“”) is not working although replace(“$”,“”) works just fine? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji