嗨我需要在字符串中匹配数学块。数学块以$$开头,以$$结尾。可以有任意数量的数学块。
例如输入可以如下:
abcd... asdfasdf
$$
math expression
$$
<another set of random words>
$$
expression
$$
...
只匹配数学表达式的正确正则表达式是什么?
感谢。
答案 0 :(得分:1)
您可以尝试/\$\$((?:\$[^\$]|[^\$])+)\$\$/g
,这将匹配$$和$$之间的任何内容,包括单个$。
let text = document.body.innerHTML;
let regex = /\$\$((?:\$[^\$]|[^\$])+)\$\$/g,
match;
while( (match = regex.exec(text)) != null) {
console.log(match[1].trim());
}
&#13;
abcd... asdfasdf
$$
math expression
$$
another set of random words
$$
expression
$$
$$
expression with a $ symbol
$$
&#13;
答案 1 :(得分:0)
我不知道什么是打字稿,但我查了一下它就像是javascript。你为什么不使用新的RegExp()? 比如新的RegExp(/^\$\$.+\$\$$/ g).exec(你的str) Char。+将检测任何字符等,直到最后找到$。您可以将其更改为您的特定条件以匹配
答案 2 :(得分:0)
假设每个奇数编号$$
启动一个数学模式块,并且每个偶数编号的一个结束前一个块,你可以在$$
上拆分字符串并取出奇数元素。阵列:
> str=`abcd... asdfasdf
$$
math expression
$$
<another set of random words>
$$
expression
$$`
> str.split("$$").filter((s, index) => index % 2 === 1)
Array [ " math expression ", " expression " ]
数组仍包含前导和尾随空格 - 您可以使用String.trim
来删除它们。