Question

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?

Was it helpful?

Solution

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 testing

The \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 syntax

EDIT:

It looks my hope for a solution didn't pan out. From the manual,

A subpattern can be named in one of three ways: (?...) or (?'name'...) as in Perl, or (?P...) as in Python. References to capturing parentheses from other parts of the pattern, such as backreferences, recursion, and conditions, can be made by name as well as by number.

And further down:

Back references to named subpatterns use the Perl syntax \k or \k'name' or the Python syntax (?P=name).

and

A subpattern that is referenced by name may appear in the pattern before or after the reference.

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top