javascriptregextypescriptkatex

How to use regex to find in between words and spaces?


I'm so frustrated and lost. I would really appreciate your help here. I'm trying to fix an issue in Katex and Guppy keyboard. I'm trying to generate a regex to find between the word matrix and find the slash that has spaces before and after and replace it with a double slash. The problem I have here is it keeps selecting all slashes between matrix


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

I want to ignore \sqrt because the slash doesn't have a couple of spaces on both sides

to something like this

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

Here is my current half working code

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


Solution

  • You can match using this regex:

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

    And replace with: $1\\$2

    RegEx Demo

    Code:

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

    RegEx Breakdown: