我有一个字符串,想用“<”和“>”替换两个字符“<”和“">”的所有实例及其周围的所有空白(没有制表符,没有换行符,可能为空),分别。
Can I do this with a one-liner replace regex expression?
缓慢而艰难的方法是
while (entry.value.indexOf(" <") > -1) {
entry.value = entry.value.replace(" <","<");
}
while (entry.value.indexOf("< ") > -1) {
entry.value = entry.value.replace("< ","<");
}
while (entry.value.indexOf(" >") > -1) {
entry.value = entry.value.replace(" >",">");
}
while (entry.value.indexOf("> ") > -1) {
entry.value = entry.value.replace("> ",">");
}
entry.value = entry.value.replace("<"," < ").replace(">"," > ");
缩短空白的说明见 Regex to replace multiple spaces with a single space ,但我不假设这两个字符周围有空格。
我的用例是将数学表达式保存在数据库中,以便使用 MathJax 在网站上呈现。这样做,就会遇到这个问题,请参阅http://docs.mathjax.org/en/latest/tex.html#tex-and-latex-in-html-documents .
典型的表达方式是
"Let $i$ such that $i<j$..."
"Let $<I>$ be an ideal in..."
(后者甚至不会在正常文本模式的预览中呈现。)
最佳答案
在此处复制粘贴 Wiktor 的评论。 \s
匹配任何空白字符,*
表示匹配 0 个或多个空白字符,[<>]
匹配任何 <
或>
,g
flag表示进行全局替换,而不是仅仅替换第一个匹配项,括号是创建一个捕获组,以便我们可以使用 $1
将匹配项作为替换字符串中的反向引用来引用。
请参阅下面的一些输入输出示例。
'<>' // => ' < > ' (two spaces between the carets)
'<\t\t\n\ \n<' // => ' < < ' (again two spaces)
'>a \t b< ' // => ' > a \t b < '
'a>\n b <c ' // => 'a > b < c '
a = 'fpo< \n>\naf ja\tb<>\t<><>asd\npfi b.<< > >';
b = a.replace(/\s*([<>])\s*/g, ' $1 ');
console.log(b);
关于Javascript:正则表达式替换两个字符及其周围的所有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47388476/