Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string everywhere except if its within quotes

I would like to replace all :) by :D, except if they are within quotes "

Example 1:

Hey man :D, how're you? :) My friend told me "this can't be true :)"

becomes

Hey man :D, how're you? :D My friend told me "this can't be true :)"

As you see, :) is not replaced if it's enclosed by ". If this condition wouldn't be there, it would be quite simple, right? I am using Javascript (jQuery) for all this.

If this is not plainly possible with a regex, what would be an alternate suggestion?

like image 913
poitroae Avatar asked Oct 26 '25 07:10

poitroae


1 Answers

Assuming no double quote is unbalanced, this is the regex that should work for you:

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

Explanation: This regex is using a positive lookahead that basically is matching 0 or more occurrences of a pair of some text until a double quote is found i.e. ([^"]*"){2} on the right hand side (RHS) of every match of :).

Which in simple term means replace a :) only if it is outside double quotes since all the matches inside double quotes will have odd number of [^"]*" matches on RHS.

Live Demo: 1. http://www.rubular.com/r/3aixZy5bYR

Live Demo: 2. http://ideone.com/C679NW

like image 116
anubhava Avatar answered Oct 27 '25 20:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!