2013-12-24 77 views

回答

2

你可以在這裏使用一個否定匹配。注意我爲這個例子跳過了\這個字面換行符。

var myString = "blah blah * Match this text Match this text\ 
      Match this text\ 
      Match this text\ 
      Match this text\ 
      *\ 
more text more text"; 

var result = myString.match(/\*([^*]*)\*/); 
console.log(result[1]); 

// => " Match this text Match this text   Match this text   Match this text   Match this text   " 

Working demo

如果你不想開頭或結尾的空白,你可以使用以下,使其成爲非貪婪。

var result = myString.match(/\*\s*([^*]*?)\s*\*/); 
console.log(result[1]); 

// => "Match this text Match this text   Match this text   Match this text   Match this text" 
+0

雖然我不想在最終輸出中使用星號,但是它可以工作。謝謝。 – BarelyConfused

+0

如果您引用了捕獲組,則星號將不在輸出中。 – hwnd

+0

沒關係我看到輸出是在索引之一。然而,我很好奇爲什麼我的輸入返回3個匹配,最後是一個數字?請參閱JsFiddle:http://jsfiddle.net/gfF33/ – BarelyConfused

0

試試這個:/(\*)([^\0].+)*(\*)/g

Live Demo

var regex = /(\*)([^\0].+)*(\*)/g; 
var input = "* Match this text Match this text (this is a line break -> \n) Match this text (\n) Match this text Match this text * more text more text"; 
if(regex.test(input)) { 
    var matches = input.match(regex); 
    for(var match in matches) { 
     alert(matches[match]); 
    } 
} 
else { 
    alert("No matches found!"); 
} 
+0

這工作雖然不是我的輸入。 – BarelyConfused

0

這些答案將幫助你倆now並在future

從控制檯:

> "blah blah * Match this text Match this text\ 
      Match this text\ 
      Match this text\ 
      Match this text\ 
      *\ 
more text more text".match(/[*]([^*]*)[*]/)[1] 

" Match this text Match this text   Match this text   Match this text   Match this text   " 
+0

謝謝我會考慮這一點。 – BarelyConfused

相關問題