Python 如何通过正则表达式将字符串的一部分替换为模式的一部分?
例如,我有如下字符串:Python 如何通过正则表达式将字符串的一部分替换为模式的一部分?,python,regex,Python,Regex,例如,我有如下字符串: string s = "chapter1 in chapters" 如何将其替换为正则表达式: s = "chapter 1 in chapters" 例如我只需要在“章节”和其编号之间插入空格(如果存在)re.sub(r'chapter\d+,r'chapter\d+,s)不起作用 您可以使用lookarounds: >>> s = "chapter1 in chapters" >>> print re.sub(r"(?<=
string s = "chapter1 in chapters"
如何将其替换为正则表达式:
s = "chapter 1 in chapters"
例如我只需要在“章节”和其编号之间插入空格(如果存在)
re.sub(r'chapter\d+,r'chapter\d+,s)
不起作用 您可以使用lookarounds:
>>> s = "chapter1 in chapters"
>>> print re.sub(r"(?<=\bchapter)(?=\d)", ' ', s)
chapter 1 in chapters
>>s=“章节中的第1章”
>>>打印re.sub(r)(?您可以使用lookarounds:
>>> s = "chapter1 in chapters"
>>> print re.sub(r"(?<=\bchapter)(?=\d)", ' ', s)
chapter 1 in chapters
>>s=“章节中的第1章”
>>>打印re.sub(r)(?您可以使用捕获组,类似这样的-
>>> s = "chapter1 in chapters"
>>> re.sub(r'chapter(\d+)',r'chapter \1',s)
'chapter 1 in chapters'
您可以使用捕获组,例如-
>>> s = "chapter1 in chapters"
>>> re.sub(r'chapter(\d+)',r'chapter \1',s)
'chapter 1 in chapters'