简体   繁体   中英

python: replacing exact with minus sign

Given the following string:

"-local locally local test local."

my objective is to replace the string "local" with "we" such that the result becomes

"-local locally we test local."

so far (with the help from the guys here at stackoverflow: Python: find exact match ) I have been able to come up with the following regular expression:

variable='local'
re.sub(r'\b%s([\b\s])' %variable, r'we\1', "-local locally local test local.")

However I have two problems with this code:

  1. The search goes through the minus sign and the output becomes:

     '-we locally we test local.' 

    where it should have been

     '-local locally we test local.' 
  2. searching for a string starting with a minus sign such as "-local" fails the search

You could separate the string into substrings using the spaces as the delimiter. Then check each string, replace if it matches what you are looking for, and recombine them.

Certainly not efficient though :)

Try the following:

re.sub(r'(^|\s)%s($|\s)' % re.escape(variable), r'\1we\2', some_string)

The regex that was suggested in the other question is kind of odd, since \\b in a character class means a backspace character.

Basically what you have now is a regex that searches for your target string with a word boundary at the beginning (going from a word character to a non-word character or vice versa), and a whitespace character at the end.

Since you don't want to match the final "local" since it is followed by a period, I don't think that word boundaries are the way to go here, instead you should look for whitespace or beginning/end of string, which is what the above regex does.

I also used re.escape on the variable, that way if you include a characters in your target string like . or $ that usually have special meanings, they will be escaped and interpreted as literal characters.

Examples:

>>> s = "-local locally local test local."
>>> variable = 'local'
>>> re.sub(r'(^|\s)%s($|\s)' % re.escape(variable), r'\1we\2', s)
'-local locally we test local.'
>>> variable = '-local'
>>> re.sub(r'(^|\s)%s($|\s)' % re.escape(variable), r'\1we\2', s)
'we locally local test local.'
sed 's/ local / we /g' filename

我不使用python,但想法只是在模式中本地的前后放置一个空格,并在替换中包含空格。

If you just want to replace all occurences of the word that are separeted by spaces, you could split the string and operate on the resulting list:

search = "local"
replace = "we"
s = "-local locally local test local."
result = ' '.join([x if not x == search else replace for x in s.split(" ")])

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