2012-10-15 31 views
3

我使用正則表達式如下匹配所有的話:正則表達式匹配所有的話,除了那些在括號 - JavaScript的

mystr.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) {...} 

注意的話可以包含特殊字符,如德國日爾曼 如何匹配括號內的所有單詞?

如果我有以下字符串:

here wäre c'è (don't match this one) match this 

我想獲得以下輸出:

here 
wäre 
c'è 
match 
this 

後面的空格並不真正的問題。 有沒有一種簡單的方法來實現這與JavaScript的正則表達式?

編輯: 我不能刪除括號中的文本,因爲最後一個字符串「mystr」也應該包含此文本,而字符串操作將在匹配的文本上執行。載於「myStr的」最後一個字符串看起來是這樣的:

Here Wäre C'è (don't match this one) Match This 
+1

我不認爲這是有可能使用單正則表達式,可能你需要首先用他們的內容去掉括號。 –

+0

你是否需要考慮嵌套(像這個(或甚至這個))圓括號?如果是這樣,您將不得不對嵌套施加上限或轉到非基於RE的解決方案。 – Vatine

+0

不需要考慮嵌套括號。可以有幾個菜式,但它們不會嵌套。例如「(像這樣)和like(this)」 – thomasf

回答

4

試試這個:

var str = "here wäre c'è (don't match this one) match this"; 

str.replace(/\([^\)]*\)/g, '') // remove text inside parens (& parens) 
    .match(/(\S+)/g);   // match remaining text 

// ["here", "wäre", "c'è", "match", "this"] 
+0

順便說一句,parens在角色類中沒有意義,因此它們不需要被轉義 - '[^)]'完全沒問題。對於任何其他元字符也是如此。 – Tomalak

+0

是的,確實如此。即使沒有必要,我總是逃避特殊字符作爲個人習慣。 – fcalderan

+0

謝謝Fabrizio,但我的問題還不夠具體。我不能刪除括號中的字符串,因爲應該返回包括括號中的文本的整個字符串,同時會對匹配執行字符串操作。 – thomasf

1

托馬斯,復活這個問題,因爲它有這樣的沒有提到一個簡單的解決方案,並且沒有按」 t需要替換然後匹配(一步而不是兩步)。 (發現你的問題而做一些研究的一般問題有關how to exclude patterns in regex

這是我們簡單的正則表達式(在看到它的工作on regex101,望着集團抓住在底部右圖):

\(.*?\)|([^\W_]+[^\s-]*) 

變更的左側匹配完整(parenthesized phrases)。我們將忽略這些匹配。右側與第1組匹配並捕獲單詞,並且我們知道它們是正確的單詞,因爲它們與左側的表達式不匹配。

這個程序演示瞭如何使用正則表達式(見online demo比賽):

<script> 
var subject = 'here wäre c\'è (don\'t match this one) match this'; 
var regex = /\(.*?\)|([^\W_]+[^\s-]*)/g; 
var group1Caps = []; 
var match = regex.exec(subject); 

// put Group 1 captures in an array 
while (match != null) { 
    if(match[1] != null) group1Caps.push(match[1]); 
    match = regex.exec(subject); 
} 

document.write("<br>*** Matches ***<br>"); 
if (group1Caps.length > 0) { 
    for (key in group1Caps) document.write(group1Caps[key],"<br>"); 
    } 

</script> 

參考

How to match (or replace) a pattern except in situations s1, s2, s3...

+0

請你能幫我這個http://stackoverflow.com/questions/23797093/regex-email-validation-that-allows-only-hyphens-in-the-middle-of-the-domain-and – Axel

相關問題