# How to refer to a character group without ambiguity in a regex?

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.

• 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. – 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".

### Update

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+.

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