【问题标题】:How to use regex to find in between words and spaces?如何使用正则表达式在单词和空格之间查找?
【发布时间】:2022-12-23 18:41:53
【问题描述】:

我很沮丧和失落。非常感谢您的帮助。 我正在尝试解决 Katex 和 Guppy 键盘中的问题。我正在尝试生成一个正则表达式以在单词 matrix 之间找到并找到前后有空格的 slash 并将其替换为双斜杠。我这里的问题是它一直在选择矩阵之间的所有斜线


 \left(\begin{matrix}    \sqrt[ 5  ]{ 6  \phantom{\tiny{!}}}     \   \dfrac{ 55  }{ 66  }       \end{matrix}\right)

我想忽略\sqrt,因为斜杠两边没有几个空格

像这样的事情

\left(\begin{matrix}    \sqrt[ 5  ]{ 6  \phantom{\tiny{!}}}     \\   \dfrac{ 55  }{ 66  }       \end{matrix}\right)

这是我目前的半工作代码

const regex = /matrix(.*?)\\(.*?)matrix/g;
equation = equation.replace(regex, 'matrix$1\\\\$2matrix');

【问题讨论】:

    标签: javascript regex typescript katex


    【解决方案1】:

    您可以使用此正则表达式进行匹配:

    ({matrix}.*? \)( .*?(?={matrix}))
    

    并替换为:$1\$2

    RegEx Demo

    代码:

    var equation = String.raw` left(egin{matrix}    sqrt[ 5  ]{ 6  phantom{	iny{!}}}        dfrac{ 55  }{ 66  }       end{matrix}
    ight)`;
    const re = /({matrix}.*? \)( .*?(?={matrix}))/g;
    
    equation = equation.replace(re, '$1\$2'); 
    
    console.log(equation);

    正则表达式细分:

    • ({matrix}.*? \):捕获第 1 组以匹配从 {matrix}
    • ( .*?{matrix}):捕获第 1 组以从单个空格匹配到 {matrix}
    • 作为替换,我们在两个反向引用之间插入一个

    【讨论】:

    • 另外,很抱歉,如果这是另一个话题,但是您是否推荐任何我可以了解更多关于 Guppy Keyboard 和 KaTeX 的文章?它要么很难找到,要么我没有用谷歌搜索正确的东西。
    • 我在这里的意思是,这会匹配第一个开始矩阵和最后一个结束矩阵,而不是匹配每对开始/结束矩阵吗?
    • 嘿@anubhava,这很好用,但它只替换了第一次出现的矩阵,所以当我有像这样更复杂的东西时,它只匹配第一组矩阵dfrac{ left( sqrt{ left(egin{matrix} 5 \ left(egin{matrix} 66 11 end{matrix} ight) end{matrix} ight) phantom{ iny{!}}} , sqrt[ 6 ]{ 66 phantom{ iny{!}}} ight) }{ 6 } 5 dfrac{ 22 }{ 5 }
    • 检查我更新的答案并查看新演示。它应该适用于最近的 {matrix} 对之间的多个 " / " 匹配项。
    • 太感谢了!这很好用!我正在考虑创建一个循环遍历所有函数的函数,然后应用一个更简单的正则表达式,但你的答案也做同样的事情。在性能方面不太确定。
    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多