Search code examples
javastringmatching

String Pattern Matching In Java


I want to search for a given string pattern in an input sting.

For Eg.

String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}"

Now I need to search whether the string URL contains "/{item}/". Please help me.

This is an example. Actually I need is check whether the URL contains a string matching "/{a-zA-Z0-9}/"


Solution

  • You can use the Pattern class for this. If you want to match only word characters inside the {} then you can use the following regex. \w is a shorthand for [a-zA-Z0-9_]. If you are ok with _ then use \w or else use [a-zA-Z0-9].

    String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
    Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
    Matcher matcher = pattern.matcher(URL);
    if (matcher.find()) {
        System.out.println(matcher.group(0)); //prints /{item}/
    } else {
        System.out.println("Match not found");
    }