0
$\begingroup$

I have a big string of data and most of them are in the form Name = number^{number}_{-number}, some are in the form Name = number \pm number. I what to convert the latter into the notation.

For a single line

singleLine = "c200 = 9.5^{+1.2}_{-1.4} v200 = 279^{+200}_{-100} YD = 0.360^{+0.054}_{-0.079} df2 = 0.910\\ pm 0.077 Dinc = -7.2\\ pm 5.3"

I used

StringReplace[singleLine, {("\\pm\ " ~~ y__ ~~ WhitespaceCharacter ~~ z_?LetterQ) -> ("^{+" ~~ y ~~ "}_{-" ~~ y ~~ "} " ~~ z), ("\\pm\ " ~~ y__ ~~ EndOfLine) -> ("^{+" ~~ y ~~ "}_{-" ~~ y ~~ "}")}]

and i got the desired format

"c200 = 9.5^{+1.2}_{-1.4} v200 = 279^{+200}_{-100} YD = 0.360^{+0.054}_{-0.079} df2 = 0.910^{+0.077}_{-0.077} Dinc = -7.2^{+5.3}_{-5.3}"

but when i try to use it for multiple lines

multipleLines = "c200 = 9.5^{+1.2}_{-1.4} v200 = 279^{+200}_{-100} YD = 0.360^{+0.054}_{-0.079} df2 = 0.910\\pm 0.077 Dinc = -7.2\\pm 5.3
c200 = 9.5^{+1.2}_{-1.4} v200 = 279^{+200}_{-100} YD = 0.360^{+0.054}_{-0.079} df2 = 0.910\\pm 0.077 Dinc = -7.2\\pm 5.3"

i get this

"c200 = 9.5^{+1.2}_{-1.4} v200 = 279^{+200}_{-100} YD = 0.360^{+0.054}_{-0.079} df2 = 0.910^{+0.077 Dinc = -7.2\\pm 5.3
c200 = 9.5^{+1.2}_{-1.4} v200 = 279^{+200}_{-100} YD = 0.360^{+0.054}_{-0.079} df2 = 0.910\\pm 0.077}_{-0.077 Dinc = -7.2\\pm 5.3
c200 = 9.5^{+1.2}_{-1.4} v200 = 279^{+200}_{-100} YD = 0.360^{+0.054}_{-0.079} df2 = 0.910\\pm 0.077} Dinc = -7.2^{+5.3}_{-5.3}"

I was wondering how can i properly select only the number after \pm to convert to the form that i want, and not what is after the number.

$\endgroup$
2
  • $\begingroup$ welcome to MMA SE! are you using underscores in a variable name? that's not permitted in mathematica; single_line will be interpreted as a pattern named single with head line (just as x_Integer is a pattern named x matching an Integer) which i don't think it what you want...! i'm surprised you didn't get an error when using it in StringReplace $\endgroup$
    – thorimur
    Nov 12, 2021 at 9:47
  • $\begingroup$ I am not, i just used here to not repeat the long line twice, in the actual notebook i use string line with the full string provided as imput $\endgroup$ Nov 13, 2021 at 1:32

1 Answer 1

1
$\begingroup$

I was able to solve it using Shortest[] as follows

StringReplace[
 multiple Lines, 
 "\\pm " ~~ Shortest[y__] ~~ WhitespaceCharacter -> 
  "^{+" ~~ y ~~ "}_{-" ~~ y ~~ "} "]

which works for both the single and multiple lines cases. In my specific case, the location of WhitespaceCharacter was key, even at the end of a line or string to be able to match the patter and replace it.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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