例如,我有这样的字符串:
string s = "chapter1 in chapters"
如何用正则表达式替换它:
s = "chapter 1 in chapters"
例如我只需要在“chapter”和它的数字之间插入空格(如果存在)。 re.sub(r'chapter\d+', r'chapter \d+ , s)
不起作用。
答案 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'