20

In my Android project I have a regular expression and a string, in which I should have the matched expression. The problem is, I've only found a matches() method, which returns boolean. Is there something, which returns only the matched string (for instance, if my string is "go to the shop at 12pm", I want to check if there is a time in this string (in this example - "12pm"), if it is - return it) ? Thanks in advance.

1 Answer 1

46

you should get capturing group you need. Read this. You'll find answer to your question.
Here is a simple example for you. I think you'll understand it.

Pattern p = Pattern.compile(".*?(\\d{2}(am|pm)).*");
Matcher m = p.matcher("go to the shop at 12pm");
if(m.matches())
   return m.group(1);

This will return 12pm
Actually you can get what you want with better way.

Pattern p = Pattern.compile("\\d{2}(am|pm)");
Matcher m = p.matcher("go to the shop at 12pm");
if(m.find())
   return m.group(0);    //or you can write return m.group(); result will be the same.
Sign up to request clarification or add additional context in comments.

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.