Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android regular expression - return matched string

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.

like image 818
lomza Avatar asked Feb 20 '12 18:02

lomza


1 Answers

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.
like image 136
shift66 Avatar answered Nov 09 '22 10:11

shift66