我正在尝试进行grep搜索以匹配时间。例如,我想匹配以下短语:
12 45 am in CA
It is currently 3 45 am
16 45 pm is the current time
3 23pm in a few hours
10 00 is the best time
我尝试使用:
grep '[0-12] [0-5][[0-9]]( ){0,1}(am|pm){0,1}'
现在我的输出没有意义。我是否应该逃避一些角色,如果是这些以及为什么?
答案 0 :(得分:1)
[0-12]
是Character Classes or Character Sets,它告诉正则表达式引擎只匹配多个字符中的一个。
这里0-1
将表示从0到1的范围。所以最后它只匹配0,1和2.
(0?[0-9]|1[0-2]) [0-5]?[0-9] ?([ap]m)?
说明
( group and capture to \1:
0? '0' (optional)
[0-9] any character of: '0' to '9'
| OR
1 '1'
[0-2] any character of: '0' to '2'
) end of \1
' '
[0-5] any character of: '0' to '5' (optional)
[0-9] any character of: '0' to '9'
' ' (optional)
( group and capture to \2 (optional):
[ap] any character of: 'a', 'p'
m 'm'
)? end of \2
这里也是DEMO。
( ){0,1}
可以转换为[ ]?
或仅single space followed by ?
?
匹配零和一次
(am|pm)
可以转换为[ap]m
[[0-9]]
无需使用双括号
答案 1 :(得分:0)
试试这个:
12小时合成:
\b([0]{0,1}[0-9]|1[01]) [0-5][0-9]{0,1}\s{0,1}(am|pm){0,1}
<强>输出:强>
24小时结合:
\b([01]{0,1}[0-9]|2[0-3]) [0-5][0-9]{0,1}\s{0,1}(am|pm){0,1}
<强>输出:强>
答案 2 :(得分:0)
这个怎么样?
grep '[0-9]\{1\} [0-9]\{2\}' time.test
例如,使用以下测试文件:
$ cat time.test
12 45 am in CA
It is currently 3 45 am
16 45 pm is the current time
3 23pm in a few hours
10 00 is the best time
3 is just a number
also my favorite number is 13
how about the current year 2014
输出结果为:
$ grep '[0-9]\{1\} [0-9]\{2\}' time.test
12 45 am in CA
It is currently 3 45 am
16 45 pm is the current time
3 23pm in a few hours
10 00 is the best time
由于上午和下午不一致(可能会或可能不会显示),因此可以将问题简化为grep
两个数字之间留有空格。
希望这有帮助。