1

Lets say i want to write a regular expression to replace the word Dog with the word Cat.

e.g.

Dogs are scary.

will become:

Cats are scary.

But i want this regex to be applied only if the word Dog is not inside a quote.

e.g.

Dogs are scary but my mom told me that "Dogs are cute"

will become:

Cats are scary but my mom told me that "Dogs are cute"

I have no idea how to do it. Help me please :)

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
areller
  • 4,800
  • 9
  • 29
  • 57
  • 3
    Which language are you using? – nu11p01n73R Dec 26 '14 at 13:54
  • In this specific example i use php but i think that it is irrelevant. – areller Dec 26 '14 at 13:59
  • Offcourse it is relevent. The flavour of regex used in different languages are different. There are features that are not supported by some languages such as look behind for example – nu11p01n73R Dec 26 '14 at 14:00
  • `regex` is not the most appropriate tool for this job. It can do it but the corresponding `regex` is complex and contains features that are not supported by all the languages that can handle `regex`. I would do it in two steps: first split the text in pieces that are enclosed in quotes or not (`regex` can do that) then use a simple string replacement function to do the change only in the pieces not enclosed in quotes. – axiac Dec 26 '14 at 14:16

3 Answers3

2

You can use this regex for search:

(?=(([^"]*"){2})*[^"]*$)Dogs

And replace by:

Cats

RegEx Demo

It matches text only if outside quote -- i.e. match even number of quotes after keyword dogs.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

If you're running perl or php you could use the below regex which uses the PCRE verb (*SKIP)(*F)

"[^"]*"(*SKIP)(*F)|Dog

DEMO

Then replace the matched Dog string with Cat

Community
  • 1
  • 1
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0
Dogs(?=(?:[^"]*"[^"]*")*[^"]*$)

Try this.Replace by cat.See demo.

https://regex101.com/r/dU7oN5/25

vks
  • 67,027
  • 10
  • 91
  • 124