I have a text file which contains lines of the type:
SYMATTR InstName U1
where "1" can be actually a number with 1 to 3 digits.
I want to replace the above line with the following 2 lines:
SYMATTR InstName U1
SYMATTR Value E1={E11} E2={E12} E3={E13} E4={E14} E5={E15} E6={E16} E7={E17} E8={E18}
For this, I wrote the following statement, using regular expressions (text
is a string containing the file content):
StringReplace[text,
RegularExpression["SYMATTR InstName U(\\d+)"] ->
"SYMATTR InstName U$1\nSYMATTR Value E1={E$11} E2={E$12} E3={E$13} \
E4={E$14} E5={E$15} E6={E$16} E7={E$17} E8={E$18}"]
Unfortunately, the above doesn't work because probably it tries to find $11
, $12
, etc., instead of $1
. How can I fix the replacement rule?
When I used grepWin to perform the substitutions I was able to make it work with \11
, \12
, etc., but this kind of referencing doesn't work in Mathematica. Nor it works putting braces around the backreference, as in ${1}1
.
I'm using Mathematica 11.1.
Edit: dirty trick
I've found a (hopefully) temporary solution by first introducing a special character and then removing it:
text = "SYMATTR InstName U17\nSYMATTR InstName U1";
textAnnotated =
StringReplace[
text, {RegularExpression["SYMATTR InstName U(\\d+)"] ->
"SYMATTR InstName U$1\nSYMATTR Value E1={E$1\[Alpha]1} E2={E$1\
\[Alpha]2} E3={E$1\[Alpha]3} E4={E$1\[Alpha]4} E5={E$1\[Alpha]5} \
E6={E$1\[Alpha]6} E7={E$1\[Alpha]7} E8={E$1\[Alpha]8}"}];
textAnnotated =
StringReplace[textAnnotated, {"\[Alpha]" -> ""}];
(* Output:
SYMATTR InstName U17
SYMATTR Value E1={E11} E2={E172} E3={E173} E4={E174} E5={E175} E6={E176} E7={E177} E8={E178}
SYMATTR InstName U1
SYMATTR Value E1={E11} E2={E12} E3={E13} E4={E14} E5={E15} E6={E16} E7={E17} E8={E18}
*)
I hope anyway that someone can find a cleaner solution.