简体   繁体   中英

replace every occurrence that is unquoted

I'm trying to write a regex in Vim to replace every occurrence of true with 't' and false with 'f' in an SQL file. To complicate this, I shouldn't replace true or false when they occur anywhere inside quotes.

I'm using the following regex which almost works:

%s/\v^(([^'"]*)|(.*('.*'|".*").*)*)\zs((t)rue|(f)alse)/'\6\7'/
#       no qts or even number of qts   \6     \7

But with one small problem: It only replaces one set of true s and false s per run. Eg (matches highlighted in bold):

INSERT INTO pages VALUES (42, NULL, 'string', true, '', NULL, true, false , 1); INSERT INTO pages VALUES (42, NULL, 'string', true, NULL, true, false , 1); INSERT INTO pages VALUES (42, NULL, true , '', NULL, true, false, 1); INSERT INTO pages VALUES (42, NULL, true, NULL, true, false , 1);

I've tried all sorts of stuff, and I've searched the internet but can't find anything, so I'm stuck. Are there any regex wizards here who know how I can fix this?

A Vim or Ruby solution would be ideal, but a general solution would be helpful as well.

FYI: This is for a rake task that pulls the remote PG database into a local SQLite3 database.

Using Vim substitute along with negative look-behinds and negative look-aheads, along with taking some inspiration from your current attempt:

%s/\([\S"']\)\@<!\(\(t\)rue\|\(\(f\)alse\)\)\([\S"']\)\@!/'\3\5'/g

The following

INSERT INTO pages VALUES (42, NULL, 'string true', true, '', NULL, true, false, 1);
INSERT INTO pages VALUES (42, NULL, "string false", true,     NULL, true, false, 1);
INSERT INTO pages VALUES (42, NULL,           true, '', NULL, true, false, 1);
INSERT INTO pages VALUES (42, NULL,           true,     NULL, true, false, 1);

Turns into:

INSERT INTO pages VALUES (42, NULL, 'string true', 't', '', NULL, 't', 'f', 1);
INSERT INTO pages VALUES (42, NULL, "string false", 't',     NULL, 't', 'f', 1);
INSERT INTO pages VALUES (42, NULL,           't', '', NULL, 't', 'f', 1);
INSERT INTO pages VALUES (42, NULL,           't',     NULL, 't', 'f', 1);

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