2

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');

timmyx
  • 166
  • 9

1 Answers1

3

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:

  • ({matrix}.*? \\): Capture group #1 to match from {matrix} to \
  • ( .*?{matrix}): Capture group #1 to match from a single space to {matrix}
  • In replacement we insert a \ between 2 back-references
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Also, sorry if it's another topic, but do you recommend any article where I can learn more about Guppy Keyboard and KaTeX? It's either hard to find or I'm not googling things right. – timmyx Dec 06 '22 at 20:42
  • What I mean here, will this match the very first begin matrix and the very last end matrix instead of matching each pair of begin/end? – timmyx Dec 06 '22 at 20:49
  • Hey @anubhava, this works perfectly but it only replaces the first occurrence of matrix so when I have something more complex like this, it only matches the first group of matrix `\dfrac{ \left( \sqrt{ \left(\begin{matrix} 5 \\ \left(\begin{matrix} 66 \ 11 \end{matrix}\right) \end{matrix}\right) \phantom{\tiny{!}}} , \sqrt[ 6 ]{ 66 \phantom{\tiny{!}}} \right) }{ 6 } 5 \dfrac{ 22 }{ 5 }` – timmyx Dec 06 '22 at 21:04
  • Check my updated answer and see new demo. It should work for multiple matches of `" / "` between closest `{matrix}` pairs. – anubhava Dec 06 '22 at 21:28
  • 1
    Thank you so much! This worked beautifully! I was thinking to create a function that loops through all of them and then applies a simpler regex but your answer does the same thing too. Not so sure in terms of performance. – timmyx Dec 09 '22 at 10:33