Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression to find repetitions of arbitrary characters

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

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

Which I want to replace with:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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 *:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading