2014-01-11 163 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); 
相關問題