红宝石正则表达式来替换方程式 [英] ruby regexp to replace equations
本文介绍了红宝石正则表达式来替换方程式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些用mathjax格式的HTML文本:
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, e.g. \(
, not \\(
, the extra \
is just escaping the first one for ruby text).
我想获得将其替代的输出,例如由latex.codecogs创建的图像,例如
I want to get the output that substitutes this into, say an image created by latex.codecogs, e.g.
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.我尝试:
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?
推荐答案
尝试:
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 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).
这篇关于红宝石正则表达式来替换方程式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文