0

Hi I am trying to get a String out of URL.

I am using Regular Expression.

String url = "http://localhost/htc/android/htc-incredible/259164-gpid";
Pattern regex = Pattern.compile("^.+/(\\d+)-gpid$"); 
Matcher tagmatch = regex.matcher( url );
System.out.println(tagmatch.group(0));

Error:

Exception in thread "main" java.lang.IllegalStateException: No match found

What I am doing wrong:

3 Answers 3

3

You need to use group(1) (the contents of the first capturing group), not group(0) (the entire match).

Oh, and of course you need to actually do a search:

tagmatch.find();
System.out.println(tagmatch.group(1));
Sign up to request clarification or add additional context in comments.

2 Comments

Updated the question with Exception.
Hell yeah! Thats what I was missing. Thanks @Tim. (Y)
1

Alternatively, you can use lastIndexOf in combination with split to get the part of the url you want. Code will look like this

url.substring(url.lastIndexOf('/')+1).split("-")[0] //prints 259164

Comments

1

You could try this:

String url = "http://localhost/htc/android/htc-incredible/259164-gpid";
url.substring(url.indexOf('/',url.indexOf("htc-incredible/"))+1,url.indexOf("-gpid"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.