2014-01-11 173 views
2

我已经JavaScript代码以下:正则表达式工作正常在C#但不是在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]); 

匹配仅具有相匹配[0] = “X = 1且y = 2” 和应该是:

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

但是这个正则表达式在C#中工作正常。

任何想法为什么发生这种情况?

谢谢你, 米格尔

回答

2
  • 指定g标志匹配多次。
  • 使用正则表达式文字(/.../),您不需要转义\
  • *贪婪地匹配。使用非贪婪版本:*?

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]"] 
+0

@CrazyCasta,没有'g'标志,'match'返回与单个项目(第一场比赛)的阵列。 (假设没有捕获组) – falsetru

+0

@CrazyCasta,'Regexp'对象没有'match'方法,但'String'没有。 – falsetru

0

尝试使用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\) and \(y=2\)的比赛,你将需要使用非贪婪操作符(*?),而不是贪婪的运营商(*)。你的正则表达式将变为:

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

尝试非贪婪:\\\[.*?\\\]|\\\(.*?\\\)。您还需要使用一个循环,如果使用.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); 
相关问题