Search code examples
javastringvariablesescapingreplaceall

Java replaceAll method with a variable string and escaped dot


I'm having a hard time figuring this one out, so I ask for your help. Here's the deal:

String str = "02-EST-WHATEVER-099-00.dwg";
String newStr = str.replaceAll("([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)", "$1$2");

The block of code above results in 02-EST-WHATEVER-099-.dwg (removed the last "00", just before the extension). Great, that's what I need!

But the RegEx I use above has to be created on the fly (the field I'm removing can be in a different position). So I used some code to create the RegEx string (here's what the result would look like if I just declared it):

String regexRemoveRev = "([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)";

Now, if I out.print(regexRemoveRev), I get ([^-_\.]+-[^-_\.]+-[^-_\.]+-[^-_\.]+-)[^-_\.]+(\.[^-_\.]+) (notice the single backslashes).

And when i try the replaceAll again, it doesn't work:

String str = "02-EST-WHATEVER-099-00.dwg";
String newStr = str.replaceAll(regexRemoveRev, "$1$2");

So I thought it could be because of the single backslashes, and I tried declaring regexRemoveRev with 4 of them, instead of just 2:

String regexRemoveRev = "([^-_\\\\.]+-[^-_\\\\.]+-[^-_\\\\.]+-[^-_\\\\.]+-)[^-_\\\\.]+(\\\\.[^-_\\\\.]+)";

The output of out.print(regexRemoveRev) is the double backslash version of the RegEx, as expected:

([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)

But the replace still doesn't work!

How do I get this to do what I want?


Solution

  • I have just wrote a short program and in both cases it works here it is:

    public class StringTest 
    {  
    
        public static void main(String[] args) 
        {  
            String str = "02-EST-WHATEVER-099-00.dwg";
    
            String newStr = str.replaceAll("([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)", "$1$2");
    
            String regexRemoveRev = "([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)";
    
            String newStr1 = str.replaceAll(regexRemoveRev, "$1$2");
    
            System.out.println("newStr: "+newStr);
            System.out.println("regexRemoveRev: "+regexRemoveRev);
            System.out.println("newStr: "+newStr1);
    
        }  
    } 
    

    The out put from the above:

    newStr: 02-EST-WHATEVER-099-.dwg
    regexRemoveRev: ([^-.]+-[^-.]+-[^-.]+-[^-.]+-)[^-.]+(.[^-.]+)
    newStr: 02-EST-WHATEVER-099-.dwg

    I am not sure why is not working for you!! or is it something else you are asking and I got wrong