[英]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 因此,如果字符串中存在beta = xx且与beta = yy不匹配,则替换
So if beta=xx does not exist in a string then append beta=yy to string 因此,如果字符串中不存在beta = xx,则将beta = yy附加到字符串中
Assuming that beta=10 is only present 0 or 1 times in the string, you could do it like this: 假设beta = 10在字符串中仅出现0或1次,则可以这样执行:
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+ 该模式将行尾视为beta = \\ d +的替代匹配,并且由于我们仅替换第一个匹配项,因此仅当行不包含beta = \\ d +时才适用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.