Skip to main content
 首页 » 编程设计

Python 正则表达式,用于拆分出现的两年的提及

2025年05月04日26luoye11

我有以下情况,在我的字符串中,我不正确地提到了形式为“(19561958)”的提及,我想将其拆分为“(1956-1958)”。我试过的正则表达式是:

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

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

请您参考如下方法:

您可以分别捕获这两年,并在两组之间插入连字符:

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

请注意,\d\d\d\d 更简洁地写为 \d{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)'