2

I have this code in Python (where _l is each line of some PHP code I'm iterating through):

_l = re.sub(r'(?:\=\s*|\=\>\s*|\(\s*|\s)(true|false|null)(?:\s*\)|\s*\;|\s*\,)', lambda pattern: pattern.group(1).upper(), _l)

The intention is for it to substitute certain primitives to uppercase, like this (in PHP):

$variable = true; // Old
$variable = TRUE; // New

But instead, I get this:

$variable TRUE

Basically I want to only replace the captured group and ignore the two non-capturing groups. It's probably horrendously obvious but I'm a Python novice :)

Thanks!

3
  • You are aware that regular expressions are not capable of correctly parsing PHP, right? This will only work at all with a very limited subset of PHP syntax. This assumes that you are not just trying to do it quick and dirty. You could do that using any text editor. Commented Dec 11, 2013 at 11:01
  • It's not meant to be perfect by any means, it's just a quick and dirty script to loop through our codebase and clear up most mistakes that people make with spacing around if statements, etc. Most of the code is just find and replaces. I'm not asking for an alternate method, more just an actual answer to my question ;) Commented Dec 11, 2013 at 11:10
  • Alright. Let's just hope that there is nothing that matches in a string literal. Commented Dec 11, 2013 at 11:12

2 Answers 2

3
_l = re.sub(r'(?:\=|\=\>|\()\s*(true|false|null)\s*(?:\)|\;|\,)', lambda pattern: pattern.group(0).upper(), _l)

this should do. However, as the other said, regex is not suitable for PHP.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that's all what I wanted to know- replace the 1 with a 0 in the pattern group. I'm aware that regexes are not suitable for parsing, I know there's a possibility of false positives, I know you should never ever use regexes on HTML or XML, I've spent enough time on stackoverflow to see this same kind of conversation a million times, I just wanted an answer to my question :) Not to sound unappreciative or anything...
Don't worry pal :) glad I could help!
Sorry to ask, can you please explain what the lambda does?
1

For the example above, one can just replace every single = true;:

php_script.replace('= true;', '= TRUE;')

And similarly for other needs.

But, as @elusive pointed out, regular expressions are not really suitable for parsing PHP files. A good text editor can do this.

1 Comment

There are loads of cases where it's not like this though. People may write $var=true ;, and then there are all other things like arrays, conditional statements, etc etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.