Replacing unquoted words in Python only

I am looking for a way to replace a word, but only when it is not surrounded by quotes.

For example, Replace HellowithHi

Hello 'Hello' Nothing & rightarrow; Hi 'Hello' Nothing

Since it 'Hello'is in quotation marks, it is not replaced, but the first one Hellodoes because it is not wrapped in quotation marks.

Any help would be great!

+3
source share
6 answers

Regular expressions are awesome:

>>>import re

>>>expression = re.compile("(?!(\"|'))Hello(?!(\"|'))")
>>>expression.sub("Hi",'This string says "Hello" and Hello')

This string says "Hello" and Hi

The only problem is that it also cannot replace "Hello and Hello", if this becomes a problem, you can add specific cases to them.

+3
source

( , ).

In [2]: print s
Hello 'Hello' Nothing
In [3]: import re
In [4]: re.sub("(?<!')Hello(?!')", 'Hi', s)
Out[4]: "Hi 'Hello' Nothing"
+1

:

>>> import re
>>> re.sub(r'([^"\']|^)Hello([^"\']|$)', r'\1Hi\2', "Hello mate")
'Hi mate'
>>> re.sub(r'([^"\']|^)Hello([^"\']|$)', r'\1Hi\2', "'Hello' mate")
"'Hello' mate"

'([^"\']|^)Hello([^"\']|$)' " , - , ".

+1

:

import re

def callback(match):
   rep = 'Hi'
   return match.group(1)+rep+match.group(2)

your_string = "Hello 'Hello' Nothing"
print re.sub("([^\']|^)Hello([^\']|$)", callback, your_string)

Hello, -, ' (^ in [] -, ). |^ |$ Hello, .

Hi ( , ).

0

Use the substring function to find all occurrences of the word that you want to replace, for each word look at one index preceding what the substring function returns and see if there is a quote.

eg. Hello. Hello. Nothing.

The substring function returns 0 - so, of course, there is no quotation The substring function returns 6 - the check string [5] - theres quote, look for the following ocurance

How can you continue checking with a substring function? something like that:

startindex=0
while(!done):
      index=substr(string, startindex)
      if(str[index-1] == "'")
            startindex=index 
            continue

from here you will understand it

0
source

This works for your test case.

import re
foo = "Hello 'Hello' Nothing"
mt = re.search(r"[^']Hello(\s+.*)", foo)
if mt:
   foo = 'Hi' + match.group(1)
0
source

All Articles