1
$\begingroup$

An example of StringReplace and RegularExpression :

StringReplace["czAB26fgsgAB5ac77bd", RegularExpression["AB[0-9]"] -> "XXX"]
"czXXX6fgsgXXXac77bd"

The above example is easy.

Now to get "czAB2XXX6fgsgAB5XXXac77bd", I tried

StringReplace["czAB26fgsgAB5ac77bd", v : RegularExpression["AB[0-9]"] -> (v <> "XXX")]
"czAB2XXX6fgsgAB5XXXac77bd"

I succeeded to get the result, but with an error message :

StringJoin::string: String expected at position 1 in v<>XXX.

What is the reason for the error message? What is the correct method? (not showing the error message)

$\endgroup$
4
  • 1
    $\begingroup$ Replace -> by :>? $\endgroup$
    – user293787
    Commented Oct 24, 2022 at 10:19
  • 1
    $\begingroup$ Thank you, I understood. If you execute a<>b, then MMA will say a,b must be string. The question can be understood in the similar context. $\endgroup$
    – imida k
    Commented Oct 24, 2022 at 11:41
  • 1
    $\begingroup$ Exactly. With -> it will evaluate v <> ... immediately, when v is just a symbol and not yet a string, and give the warning. With :> it will evaluate v <> ... only later, when v is an actual string. $\endgroup$
    – user293787
    Commented Oct 24, 2022 at 11:43
  • 1
    $\begingroup$ For the benefit of page visitors and using Mathematica's StringExpression syntax: StringReplace["czAB26fgsgAB5ac77bd", k : ("AB" ~~ DigitCharacter) :> ToString@k <> "XXX"] $\endgroup$
    – Syed
    Commented Oct 24, 2022 at 15:23

0