From what I can gather from the Pharo documentation on regex, I can define a regular expression object such as:
re := '(foo|re)bar' asRegex
And I can replace the matched regex with a string via this:
re copy: 'foobar blah rebar' replacingMatchesWith: 'meh'
Which will result in: `'meh blah meh'.
So far, so good. But I want to replace the 'bar'
and leave the prefix alone. Therefore, I need a variable to handle the captured parenthetical:
re copy: 'foobar blah rebar' replacingMatchesWith: '%1meh'
And I want the result: 'foomeh blah remeh'
. However, this just gives me: '%1meh blah %1meh'
. I also tried using \1
, or \\1
, or $1
, or {1}
and got the literal string replacement, e.g., '\1meh blah \1meh'
as a result.
I can do this easily enough in GNU Smalltalk with:
'foobar blah rebar' replacingAllRegex: '(foo|re)bar' with: '%1meh'
But I can't find anywhere in the Pharo regex documentation that tells me how I can do this in Pharo. I've done a bunch of googling for Pharo regex as well, but not turned up anything. Is this capability part of the RxMatcher class or some other Pharo regex class?
\1
, or\\1
or$1
(perhaps, withmatchesReplacedWith
)? Capturing groups are supported, it is clear from what matching can do in Pharo, but there is no hint on whether backreferences are supported as parts of replacement patterns. – Emmert\1
,\\1
, and$1
as well. In each case, the replacement was the literal string. I updated my question indicating those attempts. I see capturing groups are supported as far as matching goes. There are examples in the documentation for capturing and enumerating the captures. However, nothing about backreferencing them in a replacement string. This seems fundamental to regex find/replace to me, so I'm surprised it's not supported. – Stig