You need to escape the key using re.escape()
:
somedata = re.sub(re.escape(key), 'newvalue', somedata)
otherwise the contents will be interpreted as a regular expression.
You are not using regular expressions at all here, so you may as well just use:
somedata = somedata.replace(key, 'newvalue')
If you wanted to replace only whole words (so with whitespace or punctuation markes around them, at the start or end of the input string), you need to some kind of boundary anchors, at which point it makes sense to use regular expressions. If all you have are alphanumeric words (plus underscores),
would work:
somedata = re.sub(r'{}'.format(re.escape(key)), 'newvalue', somedata)
This puts
before and after the string you wanted to replace, so that baz
in foo baz bar
is changed, but foo bazbaz bar
is not.
For input that involves non-alphanumeric 'words', you'd need to match whitespace-or-start and whitespace-or-end anchors with look-aheads and look-behinds:
somedata = re.sub(r'(?:^|(?<=s)){}(?:$|(?=s))'.format(re.escape(key)), 'newvalue', somedata)
Here the pattern (?:^|(?<=s))
uses two anchors, the start-of-string anchor and a look-behind assertion, to match the places where there is either the start of the string or a space immediately to the left. Similarly (?:$|(?=s)
does the same for the other end, matching the end of the string or a position followed by a space.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…