Regular expression to find repetitions of arbitrary characters

Advertisements

I have a large PHP codebase with many instances of this pattern:

$result = $expression? $expression: $alternate;

Which I want to replace with:

$result = $expression ?: $alternate;

Here $expression can be anything like $this->system->cache('1234'). It will usually start with $, and usually not have any spaces in it. Those few that don’t start with $ or have spaces, I can review manually.

I can get a RegEx to match the above, allowing for optional whitespace:

(\$[^? ]+) *\? *(\$[^: ]+) *:

But this won’t guarantee that group 1 and group 2 are the same.

Is there a way to match these patterns?

>Solution :

You can use backreference \1 — reference to the first matching group, i.e.:

(\$[^? ]+) *\? *\1 *:

Leave a ReplyCancel reply