gpt4 book ai didi

java - 正则表达式在字符串中查找时间

转载 作者:行者123 更新时间:2023-11-30 04:40:04 26 4
gpt4 key购买 nike

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

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

谢谢!

最佳答案

试试这个:(?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());
}

关于java - 正则表达式在字符串中查找时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12504012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com