如何通过正则表达式替换部分字符串并保存部分模式?

时间:2015-09-15 06:53:13

标签: python regex

例如,我有这样的字符串:

string s = "chapter1 in chapters"

如何用正则表达式替换它:

s = "chapter 1 in chapters"

例如我只需要在“chapter”和它的数字之间插入空格(如果存在)。 re.sub(r'chapter\d+', r'chapter \d+ , s)不起作用。

2 个答案:

答案 0 :(得分:3)

您可以使用外观:

>>> s = "chapter1 in chapters"
>>> print re.sub(r"(?<=\bchapter)(?=\d)", ' ', s)
chapter 1 in chapters

RegEx分手:

(?<=\bchapter)  # asserts a position where preceding text is chapter
(?=d)           # asserts a position where next char is a digit

答案 1 :(得分:2)

你可以使用捕获组,像这样 -

>>> s = "chapter1 in chapters"
>>> re.sub(r'chapter(\d+)',r'chapter \1',s)
'chapter 1 in chapters'