【问题标题】:ruby regexp to replace equationsruby 正则表达式替换方程
【发布时间】:2012-10-21 09:26:19
【问题描述】:

我有一些 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"/> "

使用红宝石。我试试:

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

但这并不成功,只返回原始输入。我错过了什么?如何适当地构建此查询?

【问题讨论】:

标签: ruby regex gsub


【解决方案1】:

不确定您的正则表达式是否正确 - 但在 Ruby 中,正则表达式由 // 分隔,请尝试如下:

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

您正在尝试进行字符串替换,当然 gsub 没有找到包含 (\\[)(.*?)(\\]) 的字符串

【讨论】:

    【解决方案2】:

    试试:

    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
    • 第一个参数没有转义\

    还有一些其他小的格式化内容(空格等)。

    【讨论】:

    • 太棒了,感谢您解决这个问题。 regexpr 语言之间的差异之大令人惊讶。感谢您的良好解释和干净的 reg 表达式!
    猜你喜欢
    • 2015-07-25
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 2019-01-24
    • 2015-01-24
    • 1970-01-01
    相关资源
    最近更新 更多