سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

What if there are several ID's that are passed (which is valid)?

IMHO I wouild rather do somethis more like this:

URL url = new URL(<your link>);
String queryString = url.getQuery();

parse queryString into map for example of <String,List<String>> and get the value of ID key

(?<=[?&])id=(\d+)(?=(?:\&|$))

works in Regex Buddy under the Java and Perl flavor, but not in TextPad, which uses the Boost regex engine. Boost has issues with back-references.

(?<=(?:
   [?&]    //PRECEDED BY a question-mark or ampersand
))          
   id=(\d+) //"id=[one-or-more-digits]"
(?=(?:
   \&|$     //FOLLOWED BY an ampersand or the end of the input
))

This captures the digits only, and avoids issues such as capturing incorrect fields like

anotherid=123sometext

Expanding on @user1631616's answer:

Here is a sample code:

public static void main(String[] args) throws MalformedURLException {         
    URL aURL = new URL("http://localhost:1111/search?id=10&time=3200&type=abc");

    HashMap<String, String> params = new HashMap<>();
    String[] query = aURL.getQuery().split("&");
    for(String s: query) {
        String[] split = s.split("=");
        params.put(split[0],split[1]);
    }
    System.out.println(params.get("id")); 
    System.out.println(params.get("type")); 
    System.out.println(params.get("time")); 

}

That way if your HashMap param returns null you know that value was not set on the query string.

And also don't have to worry about the ordering of the parameters.

Why exactly do you want to use a regular expression to do this?

I would do it like this:

String url = "http://localhost:1111/search?id=13&time=3200&type=abc";
     String[] split = url.split("&");
     String id = "";    
     for (String s : split){
         if (s.contains("id")){
             id = s.substring(s.indexOf("id=")+3, s.length());
         }
     }

     System.out.println(id);

13

Something like this should do what you want:

(?<=id=)\d+

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top