简体   繁体   中英

ruby regexp to replace equations

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 another inline \\(y = x\\)"

(Note: equations are delimited by single slashes, eg \\( , not \\\\( , the extra \\ is just escaping the first one for ruby text).

I want to get the output that substitutes this into, say an image created by latex.codecogs, eg

desired_output = "an inline <img src="http://latex.codecogs.com/png.latex?f(x) = \frac{a}{b}\inline"/> equation, a display equation <img src="http://latex.codecogs.com/png.latex?F = m a"/> \n and another inline <img src="http://latex.codecogs.com/png.latex?y = x\inline"/> "

Using Ruby. I try:

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

But this is unsuccessful, returning only the original input. What did I miss? How do I construct this query appropriately?

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).

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 (\\\\[)(.*?)(\\\\])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM