julio
julio

Reputation: 6758

regex match regardless of spacing

I'm trying to replace an old function call with an updated function.

I'm looking for something like this:

$myvar = myclass::getmyvar();

However the tabs / spacing can vary wildly due to code formatting. How can I match for any number of tabs or spaces between the $myvar and the = myclass::getmyvar();?

I've tried variations of something like this:

$myvar[* \t]=[* ]myclass::getmyvar();

without success.

I'd like to pass it to a statement like the following:

grep -rl '$myvar[* \t]=[* ]myclass::getmyvar();' ./ | xargs sed -i 's/$myvar[* \t]=[* ]myclass::myvar();/$myvar = mynewclass::myvar();/g'

Is that the proper syntax, or should I be using egrep?

Upvotes: 2

Views: 559

Answers (4)

hall.stephenk
hall.stephenk

Reputation: 1165

I believe your problem lies with the location of your * and not escaping $, ( and ). This will yield better results.

\$myvar[ \t]*=[ ]*myclass::getmyvar\(\);

In addition, you can update it to match any whitespace using \s instead of character classes.

\$myvar\s*=\s*myclass::getmyvar\(\);

Upvotes: 1

bozdoz
bozdoz

Reputation: 12890

Should be something like this. You shouldn't include the * in the [] braces, and escape the $ and () braces:

\$myvar[\s\t]*?=[\t\s]*?myclass::getmyvar\(\);

Include *? to make the regex ungreedy.

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208725

You need to move the * outside of the character class, so to match any number of spaces or tabs you can use the following in your regex:

[ \t]*

You could use \s* as well, but note that this will also match line break characters, and it sounds like you are only interested in tabs and spaces.

Upvotes: 2

Evan Davis
Evan Davis

Reputation: 36622

You are looking for \s*, meaning 0 or more whitespace characters.

Upvotes: 3

Related Questions