1

我正在尝试使用正则表达式从以下字符串中提取时间

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) 但我认为它不允许在之前或之后使用单词。

谢谢!

4

1 回答 1

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

另一个(只有时间,没有 at / over 或任何其他词):

(?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());
}
于 2012-09-19T23:01:34.033 回答