RegEx replacement with backreference followed by a numeric literal

Is this what you want?

StringReplace[
    text
  , pre:("SYMATTR InstName U" ~~ d : DigitCharacter..) :> StringTemplate[
        "`1`\nSYMATTR Value `2`"
    ][pre, StringJoin[StringTemplate["E`1`=`2``1` "][#, d] & /@ Range[8]]]
]
"SYMATTR InstName U1
 SYMATTR Value E1=11 E2=12 E3=13 E4=14 E5=15 E6=16 E7=17 E8=18 "

Sorry I'm not very good with regex.


The parsing of Regular Expressions by Mathematica seems to be very strange sometimes, although it is a known fact that referring to captured groups is not well standardized across platforms. In cases like yours, when there is a digit following the numbering group, the engine has to decide how to treat it. Some do intelligently parse it, thus deciding that if the group 10, for example, was defined during expression parsing, then $10 would be treated as a reference to the group 10. If not, then it would consider it a reference to the group 1, followed by the digit 0. Also, some engines allow you to explicitly show what group you want to reference by using ${groupnumber} syntax. None of this works though. Maybe some of the site experts know how this is realized in MMA, but given the limitation, we can still work with regex by preventing StringJoin from evaluation before the replacement is made.

Borrowing from Kuba's answer to reduce the repetition of patterns:

text = "SYMATTR InstName U1";
StringReplace[text, 
  RegularExpression["SYMATTR InstName U(\\d+)"] -> 
    Hold@StringJoin["SYMATTR InstName U$1\nSYMATTR Value ", 
    StringTemplate[StringJoin["E`1`={E$1", "`1`} "]][#, "$1"] & /@ Range[8]]] // ReleaseHold

SYMATTR InstName U1

SYMATTR Value E1={E11} E2={E12} E3={E13} E4={E14} E5={E15} E6={E16} E7={E17} E8={E18}


If you use RuleDelayed and break the string up, the replacements will be made before the string is rejoined.

text = "SYMATTR InstName U1";
StringReplace[text, 
 RegularExpression["SYMATTR InstName U(\\d+)"] :> 
  "SYMATTR InstName U$1\nSYMATTR Value E1={E$1" <> "1} E2={E$1" <> 
   "2} E3={E$1" <> "3} E4={E$1" <> "4} E5={E$1" <> "5} E6={E$1" <> 
   "6} E7={E$1" <> "7} E8={E$1" <> "8}"]

It may seem a roundabout way to delimit $n arguments, but it's the second-to-last example in the Regular Expressions tutorial.