1

I am examining a string of text, and I am looking to change certain words in the text, ignoring anything inside quotation marks.

Example: If I wanted to replace "my" with "MY"

Hello my name is "Tom, and my favourite sport is football"

Would become

Hello MY name is "Tom, and my favourite sport is football"

I am using regex to search for the words to be replaced.

I'm writing this script in Python.

Edit: I will be searching the original text for words from a list, not literal words. It is also important to match 'whole words'.

7
  • Are you having difficulty with the regex or just getting started?
    – Al.Sal
    Aug 5, 2014 at 19:39
  • "I am using regex to search for the words to be replaced" That seems to say you have something already, could you share it?
    – wnnmaw
    Aug 5, 2014 at 19:40
  • Could there be escaped quotes, and are you only worried about double quotes?
    – rlms
    Aug 5, 2014 at 19:43
  • I don't have an issue with regex for searching what words I want to replace. I don't know how to replace some instances from others. Aug 5, 2014 at 19:44
  • @sweeneyrod Only worried about double quotes Aug 5, 2014 at 19:44

1 Answer 1

0

You can use this regex:

(\bmy\b)(?=(?:[^"]|"[^"]*")*$)

Demo

Python demo:

>>> txt='''\
... Hello my name is "Tom, and my favourite sport is football" my O my
... Hello Tom, my name is Bonney
... not mymymy'''
>>> tgt='my'
>>> print re.sub(r'(\b%s\b)(?=(?:[^"]|"[^"]*")*$)' % tgt, tgt.upper(), txt)
Hello MY name is "Tom, and my favourite sport is football" MY O MY
Hello Tom, MY name is Bonney
not mymymy
2
  • This caused an error in the demo, and still matched strings inside quotes Aug 8, 2014 at 6:19
  • What error in which demo?
    – dawg
    Aug 8, 2014 at 14:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.