正则表达式 - 字符串

时间:2015-10-10 19:28:06

标签: regex time

我正在尝试构建一个将第一次从字符串中拉出来的正则表达式。

问题是时间格式没有标准化。

以下是可能的变化。

':' with 1 hour digit before the ':' (ex. 9:00 pm)
':' with 2 hour digits before the ':' (ex. 10:00pm)
no minutes with with 1 hour digit (ex 9pm)
no minutes with with 1 hour digit (ex 10pm)

此外,在" am"之前可能存在或可能没有空格。或" pm"

这是一个示例字符串。

7:30 pm -9 pm Lorem Ipsum is simply dummy text. 9pm-10pm Lorem Ipsum is simply dummy text

我希望此字符串返回"7:30 pm"

4 个答案:

答案 0 :(得分:2)

试试这个正则表达式:

(?i)\d{1,2}(?::\d{2})?\s*[ap]m

解释

(?i)            # insensitive case
\d{1,2}         # one or two digits
(?:             # optional group
    :\d{2}      # the minutes
)?              # end optional group
\s*             # any spaces
[ap]m           # "am" or "pm"

Regex live here.

希望它有所帮助。

答案 1 :(得分:2)

您没有指定要使用的工具,这里是使用sed的简单实现:

echo '7:30 pm -9 pm Lorem Ipsum is simply dummy text. 9pm-10pm Lorem Ipsum is simply dummy text' | sed 's/\([0-2]\?[0-9]\(:[0-5][0-9]\)\? *[ap]m\).*/\1/i'

勒亘:

'[0-2]\?[0-9]'       match the hour (with 1 or 2 digits)
'\(:[0-5][0-9]\)\?'  match the minutes (optional)
' *'                 optional spaces
'[ap]m'              match am,pm,AM,PM (also Am,aM,pM,Pm)*
'.*'                 match all the rest of the string

瘾:外部\(...\)创建一组上述所有元素(后向引用),后面在正则表达式\1的替换部分中使用。 *:最后一个/i修饰符使正则表达式不区分大小写

您可以将所有内容重写为标准perl正则表达式:

/(?i)[0-2]?\d(?::[0-5]\d)?\s*[ap]m/

小红宝石代码:

#!/usr/bin/env ruby

input = "7:30 pm -9 pm Lorem Ipsum is simply dummy text. 9pm-10pm Lorem Ipsum is simply dummy text"
puts input[/(?i)[0-2]?\d(?::[0-5]\d)?\s*[ap]m/]

答案 2 :(得分:1)

使用以下表达式可以实现几乎通用的解决方案:

([012]?\d(:[0-5]\d)?\s*(pm|am|PM|AM))

它考虑捕获组,在字符串上获取所有当前时间字符串。

在javascript中,可能会进行如下测试:

var testTime = "7:30 pm -9 pm Lorem Ipsum is simply dummy text. 9pm-10pm Lorem Ipsum is simply dummy text";

var timeRex = /([012]?\d(:[0-5]\d)?\s*(pm|am|PM|AM))/g;

var firstTime = timeRex.exec(testTime)[0];

console.log(firstTime);

我真的相信有一个更好的通用解决方案。我会尝试更稳定,然后在这里发布。

答案 3 :(得分:1)

您可以使用以下正则表达式:

\d{1,2}\:?(?:\d{1,2}|)\s*[ap]m