Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何通过正则表达式将字符串的一部分替换为模式的一部分?_Python_Regex - Fatal编程技术网

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'