正则表达式在C#中运行良好,但在Javascript中运行不好

正则表达式在C#中运行良好,但在Javascript中运行不好,javascript,regex,Javascript,Regex,我有以下javascript代码: 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仅具有匹配项[0]=“x=1和y=2”,并且应为: matches[0] = "\(x=1\)"

我有以下javascript代码:

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仅具有匹配项[0]=“x=1和y=2”,并且应为:

matches[0] = "\(x=1\)"
matches[1] = "\(y=2\)"
matches[2] = "\[z=3\]"
但是这个正则表达式在C#中工作得很好

知道为什么会这样吗

谢谢,,
Miguel

尝试使用
match
函数而不是
exec
函数
exec
仅返回它找到的第一个字符串,
match
返回所有字符串(如果设置了全局标志)

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]);
如果不想将
\(x=1\)和\(y=2\)
作为匹配项,则需要使用非贪婪运算符(
*?
)而不是贪婪运算符(
*
)。您的RegExp将成为:

var latexRegex = new RegExp("\\\[.*?\\\]|\\\(.*?\\\)");
  • 指定要多次匹配的
    g
    标志。
    • 使用而不是
  • 使用正则表达式文字(
    /…/
    ),您不需要转义
    \
  • *
    非常匹配。使用非贪婪版本:
    *?


尝试非贪婪:
\\[.*?\\]\\\\(.*?\\\)
。如果像这样使用
.exec()
方法,还需要使用循环:

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

@CrazyCasta,不带
g
标志,
match
返回一个包含单个项(第一个匹配项)的数组。(假设没有捕获组)@CrazyCasta,
Regexp
对象没有
match
方法,但是
String
有。
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);