[英]ruby regexp to replace equations
我有一些mathjax格式的HTML文本:
text = "an inline \\( f(x) = \frac{a}{b} \\) equation, a display equation \\[ F = m a \\] \n and another inline \\(y = x\\)"
(注意:方程式由單斜線分隔,例如\\(
,而不是\\\\(
,額外的\\
只是逃避第一個用於ruby文本)。
我想得到替代它的輸出,例如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"/> "
使用Ruby。 我嘗試:
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
但這不成功,僅返回原始輸入。 我錯過了什么? 如何正確構造此查詢?
嘗試:
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
必須發生的重大變化:
gsub
的第一個參數應該是正則表達式(正如Anthony提到的那樣) \\\\2
(而不僅僅是\\2
)(參見rdoc ) \\
還有一些其他小的格式化的東西(空格等)。
不確定你的正則表達式是否正確 - 但在Ruby中,Regexp由//
分隔,嘗試這樣:
desired = text.gsub(/(\\[)(.*?)(\\])/, "<img src=\"http://latex.codecogs.com/png.latex?\2\" />")
你試圖做字符串替換,當然gsub沒有找到包含(\\\\[)(.*?)(\\\\])
的字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.