简体   繁体   中英

Regex replace or add substring in Python

I need a unique regex to replace a substring or add it if missing.

Example:

set beta=10
"alpha=25 beta=42 delta=43" need to become "alpha=25 beta=10 delta=43"
"alpha=25 delta=43" need to become "alpha=25 delta=43 beta=10"

This following code is functional only to replace existing value, but if the index to replace does not already exist it does not add anything.

dest = re.sub(r'(.*)(beta=\d+)( .*)',r'\1 beta=10 \3',source)

I can do that, but I need this result in one expression:

if re.search(r'beta=\d+',source):
    dest = re.sub(r'(.*)(beta=\d+)( .*)',r'\1 beta=10 \3',source)
else:
    dest = source + " beta=10"

So if beta=xx exist in a string and it doesn't match beta=yy then replace

So if beta=xx does not exist in a string then append beta=yy to string

Assuming that beta=10 is only present 0 or 1 times in the string, you could do it like this:

dest = re.sub("(beta=\d+|$)","beta=10",source+" ",1).strip()

The pattern considers the end of line to be an alternative match for beta=\\d+ and, since we're only substituting the first occurrence, it will only apply when the line does not contain beta=\\d+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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