lom*_*mza 15 java regex android
在我的Android项目中,我有一个正则表达式和一个字符串,我应该在其中有匹配的表达式.问题是,我只找到了一个matches()返回布尔值的方法.有什么东西,只返回匹配的字符串(例如,如果我的字符串是"在晚上12点去商店",我想检查这个字符串中是否有时间(在这个例子中 - "12pm"),如果它是 - 返回它)?提前致谢.
shi*_*t66 38
你应该得到你需要的捕获组.读这个.你会找到你的问题的答案.
这是一个简单的例子.我想你会明白的.
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);
Run Code Online (Sandbox Code Playgroud)
这将返回12pm
实际上你可以用更好的方式得到你想要的东西.
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.
Run Code Online (Sandbox Code Playgroud)