Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace Boolean with bool

Tags:

regex

perl

I am working on a C++ code base that was recently moved from X/Motif to Qt. I am trying to write a Perl script that will replace all occurrences of Boolean (from X) with bool. The script just does a simple replacement.

s/\bBoolean\b/bool/g

There are a few conditions.

1) We have CORBA in our code and \b matches CORBA::Boolean which should not be changed.
2) It should not match if it was found as a string (i.e. "Boolean")

Updated:

For #1, I used lookbehind

s/(?<!:)\bBoolean\b/bool/g;

For #2, I used lookahead.

s/(?<!:)\bBoolean\b(?!")/bool/g</pre>

This will most likely work for my situation but how about the following improvements?

3) Do not match if in the middle of a string (thanks nohat).
4) Do not match if in a comment. (// or /**/)

like image 871
KannoN Avatar asked Aug 29 '08 19:08

KannoN


4 Answers

s/[^:]\bBoolean\b(?!")/bool/g

This does not match strings where Boolean is at that the beginning of the line becuase [^:] is "match a character that is not :".

like image 196
KannoN Avatar answered Nov 18 '22 22:11

KannoN


Watch out with that quote-matching lookahead assertion. That'll only match if Boolean is the last part of a string, but not in the middle of the string. You'll need to match an even number of quote marks preceding the match if you want to be sure you're not in a string (assuming no multi-line strings and no escaped embedded quote marks).

like image 2
nohat Avatar answered Nov 18 '22 21:11

nohat


s/[^:]\bBoolean\b[^"]/bool/g

Edit: Rats, beaten again. +1 for beating me, good sir.

like image 1
Daniel Jennings Avatar answered Nov 18 '22 21:11

Daniel Jennings


#define Boolean bool

Let the preprocesser take care of this. Every time you see a Boolean you can either manually fix it or hope a regex doesn't make a mistake. Depending on how many macros you use you can you could dump the out of cpp.

like image 1
nimish Avatar answered Nov 18 '22 21:11

nimish