【发布时间】:2017-11-22 14:10:34
【问题描述】:
我编写了一个正则表达式,可以从 unicode 字符串中提取年份(例如,2014-2015)。正则表达式中的\d{1,2}\^ 代表月份代码,可能存在也可能不存在。
不管怎样,这是我写的代码:
# -*- coding: utf-8 -*-
import re
list_elem = '''Frank P. Smith (1886–1888)
Edgar Grant Sisson (1914–1917)
Douglas Z. Doty (1917–1918)
{{Ray Long}} (1918–1931)
Harry Payne Burton (1931–1942)
Frances Whiting (1942–1945)
Arthur Gordon (1946–1948)'''
period_regex = ur'(\d{1,2}\^)?\s?\d{4}\s?(–|-)\s?(\d{1,2}\^)?\s?\d{4}' #regex for checking if its a single year or period
#checking if a normal regex works
print re.search(r'W', list_elem, flags=re.IGNORECASE)
print re.findall(r'W\w+', list_elem, flags=re.IGNORECASE)
#main regex
print re.search(period_regex, list_elem, flags=re.IGNORECASE)
print re.findall(period_regex, list_elem, flags=re.IGNORECASE)
输出是:
<_sre.SRE_Match object at 0x7f8bfd1b5510>
['Whiting']
None
[]
我编写的正则表达式似乎工作正常。这是正则表达式的链接:https://regex101.com/r/scAtgw/2
但是,当我运行我的程序时,我仍然得到一个空匹配。任何想法我做错了什么??
【问题讨论】:
-
可能与Unicode有关。在这里,it works。顺便说一句,如果您只需要获得所有匹配项,我认为您需要将所有捕获组替换为非捕获组。喜欢
r'(?:\d{1,2}\^)?\s?\d{4}\s?[–-]\s?(?:\d{1,2}\^)?\s?\d{4}' -
@WiktorStribiżew 是的,这是一个更好的正则表达式,可以满足我的要求,但我仍然无法在我的机器上找到任何匹配项。任何想法如何解决与 unicode 相关的问题?
-
您需要通过在其声明中添加
u""前缀来使list_elem成为Unicode 字符串。见ideone.com/0d4nqv。 -
@WiktorStribiżew 我这样做了,仍然没有结果:(
-
看,它在这里工作 - ideone.com/Ltw4rA。