2

I have the following javascript code:

var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)");
var matches = latexRegex.exec(markdown);

alert(matches[0]);

matches has only matches[0] = "x=1 and y=2" and should be:

matches[0] = "\(x=1\)"
matches[1] = "\(y=2\)"
matches[2] = "\[z=3\]"

But this regex works fine in C#.

Any idea why this happens?

Thank You, Miguel

3 Answers 3

2
  • Specify g flag to match multiple times.
  • Using regular expression literal (/.../), you don't need to escape \.
  • * matches greedily. Use non-greedy version: *?

var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = /\[.*?\]|\(.*?\)/g;
var matches = markdown.match(latexRegex);
matches // => ["(x=1)", "(y=2)", "[z=3]"]
Sign up to request clarification or add additional context in comments.

2 Comments

@CrazyCasta, Without g flag, match returns an array with single item (the first match). (Assuming there's no capturing group)
@CrazyCasta, Regexp object does not have match method, but String does.
0

Try non-greedy: \\\[.*?\\\]|\\\(.*?\\\). You need to also use a loop if using the .exec() method like so:

var res, matches = [], string = 'I have \(x=1\) and \(y=2\) and even \[z=3\]';
var exp = new RegExp('\\\[.*?\\\]|\\\(.*?\\\)', 'g');
while (res = exp.exec(string)) {
    matches.push(res[0]);
}
console.log(matches);

Comments

0

Try using the match function instead of the exec function. exec only returns the first string it finds, match returns them all, if the global flag is set.

var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]";
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)", "g");
var matches = markdown.match(latexRegex);

alert(matches[0]);
alert(matches[1]);

If you don't want to get \(x=1\) and \(y=2\) as a match, you will need to use non-greedy operators (*?) instead of greedy operators (*). Your RegExp will become:

var latexRegex = new RegExp("\\\[.*?\\\]|\\\(.*?\\\)");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.