我陷入了正则表达式操作。我正在尝试编写一个可选表达式来查找字符串中的日期
我有三个字符串 a、b 和 c,如下所示
a = '(sam was born on 11 Oct 1990)'
b = 'sam was born on Oct 1990'
c = 'sam was born on 1990'
我想写一个表达式,使得 for
a I get output '11 Oct 1990'
b I get output 'Oct 1990'
c I get output '1990'
我能够获取 a 和 b 的正确输出,但对于 c 我无法获取。但是当我将 c 更改为
c = 'sam was born on 1990' -- with two spaces between on and 1990
我获取了正确的输出。
我使用的正则表达式是:
print re.findall(r"((11)?[\s\(](((Nov|Oct))?([\s\(-]|,\s)(1990|1991)))", a)
我获取的输出是:
Output for a : [('11 Oct 1990', '11', 'Oct 1990', 'Oct', 'Oct', ' ', '1990')]
Ouptut for b : [(' Oct 1990', '', 'Oct 1990', 'Oct', 'Oct', ' ', '1990')]
Ouptut for c : []
如有任何帮助,我们将不胜感激。谢谢
最佳答案
你可以使用这个:
regex = re.compile(r'((?:11)?[\s\(](?:(?:(?:Nov|Oct))?(?:[\s\(?:-]|,\s)?(?:1990|1991)))')
它和你的一样,但是对于非捕获 block ,只有外部的 block 捕获
关于python - 可选的正则表达式操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36157863/