简体   繁体   English

Python 正则表达式替换 substring 和值

[英]Python regex replace substring and value

I would like to replace substring(s) {with a certain format} from a string.我想从字符串中替换子字符串{以某种格式}。 And if no substring was found, append some string to the original string.如果没有找到 substring ,则 append 一些字符串到原始字符串。

That might have been a bit confusing, so let me try to give an example.这可能有点令人困惑,所以让我试着举个例子。 I want to replace AGE/age {digits} with AGE XXX .我想用AGE XXX替换AGE/age {digits} And if none is found, append NO AGE FOUND .如果没有找到, append NO AGE FOUND

For example, say we have a string例如,假设我们有一个字符串

He is in old age. At AGE 51, something something. At age 12 he bla bla.

This should be replaced with这应该替换为

He is in old age. At AGE XXX, something something. At AGE XXX he bla bla.

Another example:另一个例子:

He is in old age. Something something bla bla.

Will be replaced with:将替换为:

He is in old age. Something something bla bla. NO AGE FOUND

This may not make sense at all, just trying to create an example similar to the situation I have.这可能根本没有意义,只是试图创建一个类似于我的情况的示例。

You can use re.subn :您可以使用re.subn

import re

def redact(text):
    redacted, n_found = re.subn(r"(age|AGE)\s+\d+", "age XXX", text)
    return redacted if n_found else redacted + " NO AGE FOUND"

print(redact("He is in old age.  At AGE 51, something something.  At age 12 he bla bla."))
# He is in old age.  At age XXX, something something.  At age XXX he bla bla.

print(redact("He is in old age.  Something something bla bla."))
# He is in old age.  Something something bla bla. NO AGE FOUND

Specifically, re.subn returns a tuple containing the new string and the number of substitutions made.具体来说, re.subn返回一个包含新字符串和替换次数的元组。

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

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