Search code examples
javaregexstringreplaceall

conditional replaceAll java


I have html code with img src tags pointing to urls. Some have mysite.com/myimage.png as src others have mysite.com/1234/12/12/myimage.png. I want to replace these urls with a cache file path. Im looking for something like this.

String website = "mysite.com"    
String text = webContent.replaceAll(website+ "\\d{4}\\/\\d{2}\\/\\d{2}", String.valueOf(cacheDir));

This code however does not work when the url does not have the extra date stamp at the end. Does anyone know how i might achieve this? Thanks!


Solution

  • Try this one

    mysite\.com/(\d{4}/\d{2}/\d{2}/)?
    

    here ? means zero or more occurance


    Note: use escape character \. for dot match because .(dot) is already used in regex

    Sample code :

    String[] webContents = new String[] { "mysite.com/myimage.png",
            "mysite.com/1234/12/12/myimage.png" };
    
    for (String webContent : webContents) {
        String text = webContent.replaceAll("mysite\\.com/(\\d{4}/\\d{2}/\\d{2}/)?",
                String.valueOf("mysite.com/abc/"));
        System.out.println(text);
    }
    

    output:

    mysite.com/abc/myimage.png
    mysite.com/abc/myimage.png
    

    enter image description here