Extract a substring by using regex doesn't work

63 views Asked by At

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

5

There are 5 answers

3
agad On BEST ANSWER

You need to escape brackets:

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

Your RegEx is lack of \\

Pattern p = Pattern.compile("\\[(.*?)]");
0
Jithin Krishnan On

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

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

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("\\[(.*?)\\]");
0
Alexis C. On

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);