Suppose I want to realize a replacement in a string: "aabbcc11dd ee" -> "aabbcc112dd ee", I can use a regex like this within StringReplace:

RegularExpression["[a-z](\\d+)[a-z]"] -> "$12"

well, if only the right-hand side "$12" was interpreted as "the group 1 with the digit 2" instead of "the group 12".

So, in Wolfram's regex, is there any syntax setup to eliminate this ambiguity? I know that, for example, in Python there is something like '\g<i>', which, because of the angled brackets, allows no room for ambiguity.

  • 1
    $\begingroup$ Not sure, but in general the StringExpression and pattern system is actually competitive with regex and allows much more sophisticated binding so I tend to use that. $\endgroup$ – b3m2a1 Nov 11 '18 at 3:41

I think what you need is this.

StringReplace["aabbcc11dd  ee", RegularExpression["(\\d+)"] :> "$1" <> "2"]

"aabbcc112dd ee"

Note the use of RuleDelayed (:>) as well as "$1" <> "2".


Doing it without RegularExpression.

StringReplace["aabbcc11dd  ee", x : DigitCharacter .. :> x <> "2"]

"aabbcc112dd ee"

Note that with this approach the equivalent of a regex group is a named character pattern — in this case, DigitCharacter .., the equivalent to regex \\d+.

  • $\begingroup$ Great! ~~ works instead of <>, too. $\endgroup$ – Αλέξανδρος Ζεγγ Nov 11 '18 at 9:06
  • $\begingroup$ @ΑλέξανδροςΖεγγ. Note correction to the regular expression. $\endgroup$ – m_goldberg Nov 11 '18 at 9:11
  • $\begingroup$ OK, I see. Thx! $\endgroup$ – Αλέξανδρος Ζεγγ Nov 11 '18 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.