我正在尝试使用正则表达式从以下字符串中提取时间
Free concert at 8 pm over there
Free concert at 8pm over there
Free concert at 8:30 pm over there
Free concert at 8:30pm over there
有人知道如何在java中使用Regex吗?
我已经尝试了以下(1 [012] | [1-9]):[0-5] 0-9?(?i)(am | pm)但我不认为它允许以前的单词或后。
谢谢!
答案 0 :(得分:2)
试试这个:(?i)at (.+?) over
示例:强>
String str = "Free concert at 8 pm over there"
+ "Free concert at 8pm over there"
+ "Free concert at 8:30 pm over there"
+ "Free concert at 8:30pm over there";
Pattern p = Pattern.compile("(?i)at (.+?) over");
Matcher m = p.matcher(str);
while( m.find() )
{
System.out.println(m.group(1));
}
<强>输出:强>
8 pm
8pm
8:30 pm
8:30pm
另一个(仅限时间,没有/或超过任何其他词):
(?i)[0-9]{1,2}:??[0-9]{0,2}\\s??(?:am|pm)
但是你不需要group(1)
(你可以group(0)
或只是group()
)!
示例:强>
String str = "Free concert at 8 pm over there"
+ "Free concert at 8pm over there"
+ "Free concert at 8:30 pm over there"
+ "Free concert at 8:30pm over there";
Pattern p = Pattern.compile("(?i)[0-9]{1,2}:??[0-9]{0,2}\\s??(?:am|pm)");
Matcher m = p.matcher(str);
while( m.find() )
{
System.out.println(m.group());
}