Python正则表达式,用于拆分出现在altogeth中的两年

2024-04-26 11:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的例子,在我的字符串中,我有不正确的格式提到形式“(1956-1958)”,我想分成“(1956-1958)”。我尝试的正则表达式是:

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

但这让我回过神来”(19561958-)。我怎样才能达到我的目的?非常感谢


Tags: 字符串import目的re格式形式例子
3条回答

您可以使用捕获组或环顾四周

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)'

或者

通过环顾四周

>>> a = "(19561958)"
>>> re.sub(r"(?<=\(\d{4})(?=\d{4}\))", r"-", a)
'(1956-1958)'
  • (?<=\(\d{4})肯定的lookback,断言匹配必须以(和四位字符开头

  • (?=\d{4}\))Posiitve lookahead,断言匹配必须后跟4位数字加上)符号

  • 这里有一个边界匹配。用-替换匹配的边界将得到所需的输出

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

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

请注意,\d\d\d\d更简洁地写为\d{4}


如前所述,这将在任何八位数加上数字的前两组四位之间插入一个连字符。如果您需要匹配的括号,则可以使用look arounds显式地包含它们:

>>> 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)'

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

第二组用\2引用

相关问题 更多 >