简体   繁体   English

Python正则表达式替换字符串

[英]Python regular expression replace string

I have the following code: 我有以下代码:

 a="32<2>fdssa</2>ffdsa32"
 re.sub(r'<(\d+)>|</(\d+)>',"item",a)

The result I get: 我得到的结果是:

32itemfdssaitemffdsa32

I want the result: 我想要结果:

32<item>fdssa</item>ffdsa32

You need to capture </ part. 您需要捕获</ part。

re.sub(r'(</?)\d+>',r"\1item>",a)

Since I made / as optional, (</?) will capture < or </ 由于我将/设为可选,所以(</?)将捕获<</

Example: 例:

>>> a="32<2>fdssa</2>ffdsa32"
>>> re.sub(r'(</?)\d+>',r"\1item>",a)
'32<item>fdssa</item>ffdsa32'
>>> re.sub(r'(</?)\d+(?=>)', r'\1item', a)
'32<item>fdssa</item>ffdsa32'
  • (</?) matches < or </ captures to \\1 (</?)匹配<</捕获到\\1

  • \\d+ matches one or more digits. \\d+匹配一个或多个数字。

  • (?=>) positive look ahead, checks if the digits is followed by > , but doesn't consume them (?=>)积极向前看,检查数字后面是否有> ,但不消耗它们

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

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