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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With