5

Mathjax 形式の HTML テキストがあります。

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

(注: 方程式は単一のスラッシュで区切られます。たとえば\(、 ではなく\\(、余分な部分\はルビ テキストの最初のスラッシュをエスケープするだけです)。

これを代用する出力を取得したい、たとえばlatex.codecogsによって作成された画像など

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"/> "

ルビー使用。私は試します:

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

しかし、これは失敗し、元の入力のみが返されます。私は何を取りこぼしたか?このクエリを適切に作成するにはどうすればよいですか?

4

2 に答える 2

1

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

于 2012-10-31T20:10:46.687 に答える
0

正規表現が正しいかどうかはわかりませんが、Ruby では正規表現は で区切られています//。次のようにしてみてください。

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

あなたは文字列置換を行おうとしていましたが、もちろん gsub は以下を含む文字列を見つけられませんでした(\\[)(.*?)(\\])

于 2012-10-31T19:47:13.870 に答える