Search code examples
javaregexjava-11string-matching

Having trouble with regex in Java 11


Trying to strip server name from: //some.server.name/path/to/a/dir (finishing with /path/to/a/dir)

I have tried 3 different regexes (hardcoded works), but the other two look like they should work but are not. Can anyone point me to why ?

cat test.java

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test
{
public static void main(String[] args) throws Exception
{

        String rootPath="//server.myco.com/some/path/to/a/doc/root";
        rootPath = rootPath.replace("//[\\w.]*","");
        System.out.println("rootPath - "+rootPath);
        rootPath = rootPath.replace("//[^/]*","");
        System.out.println("rootPath - "+rootPath);
        rootPath = rootPath.replace("//server.myco.com","");
        System.out.println("rootPath - "+rootPath);

}
}

Output:

rootPath - //server.myco.com/some/path/to/a/doc/root
rootPath - //server.myco.com/some/path/to/a/doc/root
rootPath - /some/path/to/a/doc/root

Java 11.0.6:

$ java --version
openjdk 11.0.6 2020-01-14
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.6+10)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.6+10, mixed mode)

Solution

  • You should use this from the String class:

    public String replaceAll(String regex, String replacement) 
    

    instead of this:

    public String replace(CharSequence target, CharSequence replacement)
    

    When you are calling replace("//[\\w.]*","") or replace("//[^/]*",""), it's searching "//[\\w.]*" or "//[^/]*" respectively, and trying to replace with the empty string. As there is no such string in the given string, no change is there.

    But replaceAll("//[\\w.]*","") takes regex as the first argument. Hence it will work.

    Oracle Java 11 reference for String replace() and replaceAll()