简体   繁体   English

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

[英]How to replace part of string via regex with saving part of pattern?

For example, I have strings like this: 例如,我有这样的字符串:

string s = "chapter1 in chapters"

How can I replace it with regex to this: 我如何用正则表达式替换它:

s = "chapter 1 in chapters"

eg I need only to insert whitespace between "chapter" and it's number if it exists. 例如,我只需要在“章节”之间插入空格,如果存在则为数字。 re.sub(r'chapter\\d+', r'chapter \\d+ , s) doesn't work. re.sub(r'chapter\\d+', r'chapter \\d+ , s)不起作用。

You can use lookarounds: 您可以使用环顾:

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

RegEx Breakup: 正则表达式分解:

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

You can use capture groups, Something like this - 您可以使用捕获组,诸如此类-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM