简体   繁体   中英

Regex - Replace only if the pattern is not inside a quote

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

eg

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.

eg

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 :)

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

You can use this regex for search:

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

And replace by:

Cats

RegEx Demo

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

Dogs(?=(?:[^"]*"[^"]*")*[^"]*$)

Try this.Replace by cat .See demo.

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

对于更完整的功能,如果您需要变量来控制替换,请参阅https://stackoverflow.com/a/69428257/1432181了解类似问题

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