ruby regexp to replace equations

后端 未结 2 682
轻奢々
轻奢々 2021-01-18 19:41

I have a some HTML text in mathjax format:

text = \"an inline \\\\( f(x) = \\frac{a}{b} \\\\) equation, a display equation \\\\[ F = m a \\\\] \\n and anothe         


        
相关标签:
2条回答
  • 2021-01-18 20:30

    Try:

    desired = text.gsub(/\\\[\s*(.*?)\s*\\\]/, "<img src=\"http://latex.codecogs.com/png.latex?\\1\"/>") 
    desired = desired.gsub(/\\\(\s*(.*?)\s*\\\)/, "<img src=\"http://latex.codecogs.com/png.latex?\\1\inline\"/>")
    desired
    

    The important changes that had to happen:

    • The first parameter for gsub should be a regex (as Anthony mentioned)
    • If the second parameter is a double-quoted string, then the back references have to be like \\2 (instead of just \2) (see the rdoc)
    • The first parameter was not escaping the \

    There were a couple of other minor formatting things (spaces, etc).

    0 讨论(0)
  • 2021-01-18 20:30

    Not sure if your regexp is right - but in Ruby, Regexp are delimited by //, try like this :

    desired = text.gsub(/(\\[)(.*?)(\\])/, "<img src=\"http://latex.codecogs.com/png.latex?\2\" />")
    

    You were trying to do string substition, and of course gsub wasn't finding a string containing (\\[)(.*?)(\\])

    0 讨论(0)
提交回复
热议问题