繁体   English   中英

ruby regexp替换方程式

[英]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.

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