Ragnarsson
Ragnarsson

Reputation: 1825

Extract a substring by using regex doesn't work

I have a string like this:

String source = "https://1116.netrk.net/conv1?prid=478&orderid=[6aa3482b-519b-4127-abee-debcd6e39e96]"

I want to extract orderid which is inside [ ]. I wrote this method:

public String extractOrderId(String source)
{
    Pattern p = Pattern.compile("[(.*?)]");
    Matcher m = p.matcher(source);
    if (m.find())
        return m.group(1);
    else
        return "";
}

But I always get Exception

java.lang.IndexOutOfBoundsException: No group 1

Any idea what's wrong? Thanks

Upvotes: 0

Views: 67

Answers (5)

Alexis C.
Alexis C.

Reputation: 93872

Aside from using a regex you could use the URL class to extract the query:

URL url = new URL("https://1116.netrk.net/conv1?prid=478&orderid=[6aa3482b-519b-4127-abee-debcd6e39e96]");
String query = url.getQuery();

At that point the value of query is prid=478&orderid=[6aa3482b-519b-4127-abee-debcd6e39e96]. From there you can easily extract the orderid by a combination of indexOf and substring.

String searchFor = "orderid=[";
int fromIndex = query.indexOf(searchFor);
int toIndex = query.indexOf("]", fromIndex);

//6aa3482b-519b-4127-abee-debcd6e39e96
String orderId = query.substring(fromIndex+searchFor.length(), toIndex);

Upvotes: 1

Estimate
Estimate

Reputation: 1461

You have used [(.*?)]. Please refer this for the meaning of square brackets.

So in this case, you need to define the regex for the character [ and ] as well. So you need to escape those characters from the Pattern.compiler.

The following will match the requirement that you want.

Pattern p = Pattern.compile("\\[(.*?)\\]");

Upvotes: 0

Jithin Krishnan
Jithin Krishnan

Reputation: 1044

You need to use escape characters for [] , try the following

Pattern p = Pattern.compile("\\[(.*)\\]");

Upvotes: 0

agad
agad

Reputation: 2189

You need to escape brackets:

Pattern p = Pattern.compile("\\[(.*?)\\]");

Upvotes: 1

codeaholicguy
codeaholicguy

Reputation: 1691

Your RegEx is lack of \\

Pattern p = Pattern.compile("\\[(.*?)]");

Upvotes: 0

Related Questions