简体   繁体   中英

Using regex and sed command to substitute ' *' pointers in C++ code is not working

I'm a rookie programmer dealing with a C++ code that I should review and study. One of the basic task I'm with is to change the pointers notification like this:

char *name;

to this convention:

char* name;

Since my OS is Ubuntu 13.10, I thought that regex could do the job. I studied it a bit and tried different variations of a command like this:

find ./ -type f -exec sed -i -e 's/(?<=\w)\s\*(?!\s)/\* /g' {} \;

That is intended to be read as: find in string an alphanumeric, then matches with whitespace followed by asterisk, when is followed by not-a-whitespace, and replace with asterisk and whitespace. I understand that for substitution \\s cannot be used, that look ahead/behind will not enter in the match, so I played a bit with command with little success. I tried it first with Eclipse IDE 'find' menu, and regular expression seems to be properly build since it's really finding what I expect. But when I try the command, it's not changing the lines as expected, in fact they stand still the same, untouched.

I was also trying a narrower case of the above, ie to change casting to pointer like this:

(char *) another_name

into this

(char*) another_name

using this command line:

find ./ -type f -exec sed -i -e 's/(?<=\w)\s\*(?=\))/\*/g' {} \;

But seems that regex engine is not recognizing the escaped parenthesis, since it gives me "sed: -e expression #1, char 25: Unmatched ) or )".

Now I'm banging my head to the wall trying to figure out which the correct way to handle this: why the substitution is not working as expected, and why the same command using isntead an escaped parenthesis inside the positive look behind is not recognized?

Thanks in advance for any suggestion you can give.

sed does not support lookaround assertions, enable the -r flag and use extended regular expressions:

sed -i -r 's/(\w+)\s*\*(\w)/\1\* \2/g'

Ideone Demo

In Perl you can use lookaround assertions:

perl -i -pe 's/(?<=\w)\s*\*(?=\w)/\* /g'

Ideone Demo

"a rookie programmer dealing with a C++ code" probably shouldn't be automating this. Have you thought about the cases of * used for multiplication

name * another_name

or dereference?

Type t = *it;

You seem to think C++ casts live inside round brackets

(char*) name

where in fact they usualy appear inside angle ones

static_cast<char*>(name)

etc ....

You might be better of doing this one by hand to better learn what you're dealing with.

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