I am trying to replace public methods to protected methods for methods that have a comment.
This because I am using phpunit to test some of those methods, but they really don’t need to be public, so I’d like to switch them on the production server and switch back when testing.
Here is the method declaration:
public function extractFile($fileName){ //TODO: change to protected
This is the regexp:
(?<ws>^\s+)(?<pb>public)(?<fn>[^/\n]+)(?<cm>//TODO: change to protected)
If I replace it with:
\1protected\3\//TODO: change back to public for testing
It seems to be working, but what I cannot get to work is naming the replace with. I have to use \1 to get the first group. Why name the groups if you can’t access them in the replacing texts? I tried things like <ws>, $ws, $ws, but that doesn’t work.
What is the replacing text if I want to replace \1 with the <ws> named group?
The
?<ws>named group syntax is the same as that used by .NET/Perl. For those regex engines the replacement string reference for the named group is${ws}. This means your replacement string would be:${ws}protected${fn}\//TODO: change back to public for testingThe
\k<ws>reference mentioned by m.buettner is only used for backreferences in the actual regex.Extra Information:
It seems like Geany also allows use of Python style named groups:
?P<ws>is the capturing syntax\g<ws>is the replacement string syntax(?P=ws)is the regex backreference syntaxEDIT:
It looks my hope for a solution didn’t pan out. From the manual,
And further down:
and
So, my inference of the syntax for using named groups was correct. Unfortunately, they can only be used in the matching pattern. That answers your question "Why name groups…?".
How stupid is this? If you go to all the trouble to implement named groups and their usage in the matching pattern, why not also implement usage in the replacement string?