2015-06-28 56 views
1
// Pattern 
{{\s*.*?(?!contact\.firstName|contact\.lastName|contact\.phoneNumber|contact\.language)\s*}} 

// String 
test {{debug}} {{contact.language}} test {{another}} 

一個子我想匹配的子字符串是{{ }}之間不在一組特定的字符串(contact.firstNamecontact.lastNamecontact.phoneNumbercontact.language)的。現在在這個例子中,恰好我想排除的文本都有contact.。但不,它可以是任何文本,並可能包含符號和空格。匹配不包含某個子

在這個例子中,我需要匹配{{debug}}{{another}}。如果我正確理解正則表達式,它應該匹配(?!)下列出的任何內容(甚至空白)。但是,它可能會由於.*部分而保持匹配{{contact.language}}

一個人如何匹配集合中定義的以外的任何東西?我並不擅長正則表達式,因爲我不是每天都在使用它。

+1

當''的C' {{contact.language}}'由'消耗。*?',剩餘'ontact.language}}'不受任何接觸\ .firstName的'匹配|聯繫\ .lastName |聯繫\ .phoneNumber |聯繫\ .language'。 – Gumbo

+0

總之,你想放棄以'contact.'開頭的所有內容嗎? –

+0

@CasimiretHippolyte恰好我想要搜索的文本都有'contact.',但它可以是任何東西,而不僅僅是'contact.'。 – Joseph

回答

0

簡單而不是完整的正則表達式解決方案(如果我們不能拿出一個)。使用你的正則表達式,然後過濾它返回的數組。

功能碼:

var reg = /{{\s*.*?\s*}}/g; 

var testStr = "test {{debug}} {{contact.language}} test {{another}}"; 

var result = testStr.match(reg).filter(function(str){ 
    if(str === "{{contact.firstName}}" | 
     str === "{{contact.lastName}}" | 
     str === "{{contact.phoneNumber}}" | 
     str === "{{contact.language}}") { 
     return false 
    } else { 
     return true; 
    } 
}); 

console.log(result); 
// [ "{{debug}}", "{{another}}"] 
1

如果您需要使用斷言來排除這些字符串,這應該工作。

# /\{\{(?!\s*contact\.(?:firstName|lastName|phoneNumber|language)\s*\}\})(?:(?!\{\{|\}\})[\S\s])+\}\}/ 


\{\{      # Opening brace '{{' 
(?!      # Assert, not any of these after open/close braces 
     \s* 
     contact\. 
     (?: 
      firstName 
     | lastName 
     | phoneNumber 
     | language 
    ) 
     \s* 
     \}\} 
) 
(?:      # Cluster 
     (?! \{\{ | \}\})  # Assert not open/close braces 
     [\S\s]     # Grab a single character 
)+      # End cluster, do 1 or more times 
\}\}      # Closing brace '}}' 
+0

碰巧所有我不想匹配的文本都有'contact.',但實際上它可以是任何文本。 – Joseph

+0

@JosephtheDreamer - 真的不要緊,你不想匹配嗎?我的意思是,上面描述的是一個模板,用於將'stuff'放入..'\ {\ {(?!(?#stuff)\} \})(?:(?!\ {\ {| \} \})[\ S \ S])+ \} \}' – sln