Android的常规前pression - 返回匹配的字符串 [英] Android regular expression - return matched string
问题描述
在我的Android项目我有一个正规的前pression和一个字符串,其中我应该有匹配的前pression。问题是,我只找到了一个匹配()
方法,它返回boolean值。是不是有什么,仅返回匹配的字符串(例如,如果我的字符串到中午12点店,我要检查是否有此字符串时(在这个例子 - 12点),如果它是 - 返回它)?
先谢谢了。
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);
这将返回 12点
结果
其实你可以得到你想要的东西有更好的办法。
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.
这篇关于Android的常规前pression - 返回匹配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!