Search code examples
javaregexdata-extraction

Java Regex Pattern to extract data


I have incoming data something like this

http://localhost:1111/search?id=10&time=3200&type=abc
http://localhost:1111/search?time=3200&id=11&type=abc
http://localhost:1111/search?id=12
http://localhost:1111/search?id=13&time=3200&type=abc

The data is varying but not something completely random or unpredictable.

So basically how do we extract what are the IDs that are incoming in each string ignoring rest of the junk?


Solution

  • You can try using the regex id=(\d+) and extract the value of the first capturing group:

    String url = "http://localhost:1111/search?id=10&time=3200&type=abc";
    
    Pattern id = Pattern.compile("id=(\\d+)");
    
    Matcher m = id.matcher(url);
    if (m.find())
        System.out.println(m.group(1));
    
    10
    

    See Pattern and Matcher.