2015-02-08 26 views
1

我有以下情况,在我的字符串中,我有格式不正确的提及形式“(19561958)”,我想分裂成“(1956-1958) ”。我尝试的正则表达式为:Python正则表达式拆分提及两年共同出现

import re 
a = "(19561958)" 
re.sub(r"(\d\d\d\d\d\d\d\d)", r"\1-", a) 

但这返回我 “(19561958-)”。我怎样才能达到我的目的?非常感谢!

回答

2

您可以单独捕获两年,然后将两组之间的连字符:

>>> import re 
>>> re.sub(r'(\d{4})(\d{4})', r'\1-\2', '(19561958)') 
'(1956-1958)' 

注意\d\d\d\d更简洁写成\d{4}


上述代码,这将在任何八位数字的加号插入第一两组4之间的连字符。如果您需要的比赛括号,你可以用查找变通明确将它们纳入:

>>> re.sub(r''' 
    (?<=\() # make sure there's an opening parenthesis prior to the groups 
    (\d{4}) # one group of four digits 
    (\d{4}) # and a second group of four digits 
    (?=\)) # with a closing parenthesis after the two groups 
''', r'\1-\2', '(19561958)', flags=re.VERBOSE) 
'(1956-1958)' 

或者,您可以用字边界,这也将涉及例如八位数字周围的空格:

>>> re.sub(r'\b(\d{4})(\d{4})\b', r'\1-\2', '(19561958)') 
'(1956-1958)' 
2

您可以使用捕获组或环视。

re.sub(r"\((\d{4})(\d{4})\)", r"(\1-\2)", a) 

\d{4}完全匹配4位数。

实施例:

>>> a = "(19561958)" 
>>> re.sub(r"\((\d{4})(\d{4})\)", r"(\1-\2)", a) 
'(1956-1958)' 

OR

通过lookarounds。

>>> a = "(19561958)" 
>>> re.sub(r"(?<=\(\d{4})(?=\d{4}\))", r"-", a) 
'(1956-1958)' 
  • (?<=\(\d{4})正回顾后,它断言匹配必须由(和四个数字字符之前。

  • (?=\d{4}\)) Posiitve lookahead它声称匹配必须跟着4位数加)符号。

  • 这里边界得到了匹配。用-替换匹配的边界将会给你想要的输出。

2

使用两个捕获组:r"(\d\d\d\d)(\d\d\d\d)"r"(\d{4})(\d{4})"

第二组引用\2