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で正規表現を使用してこれを行う方法を知っている人はいますか?

次の (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

もう1つ(時間のみ、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 に答える