2016-06-07 65 views
1

我有一個html字符串,我需要通過正則表達式。此表達式必須以下列格式檢測MailChimp標記:*|TagName|*我需要一個正則表達式來檢測MailChimp標籤

我對正則表達式不太熟悉。我目前使用的是:\*\|([^]]*)\|\*

但他的正則表達式檢測到2個匹配之間的while字符串。因此,如果我們有:

"Sample text with user *|User_Name|*, to verify regular expression with *|Date_Value|*, and some other text"

比賽將是:

"*|User_Name|*, to verify regular expression with *|Date_Value|*" 

如果有人能告訴我如何改變表達或使用什麼,而不是單獨地檢測所有比賽。

謝謝

+0

我認爲這將有助於\ * \ | \ w + \ | \ * * – A191919

回答

2

請試試這個正則表達式:

string source = 
    "Sample text with user *|User_Name|*, to verify regular expression with *|Date_Value|*, and some other text"; 

    string pattern = @"\*\|.*?\|\*"; // please, notice ".*?" instead of ".*" 

    // ["*|User_Name|*", "*|Date_Value|*"] 
    string[] matches = Regex 
    .Matches(source, pattern) 
    .OfType<Match>() 
    .Select(match => match.Value) 
    .ToArray(); 

訣竅是在的.*?代替.* - 比賽爲幾個字母儘可能

+0

非常感謝。這解決了它! –

+0

@M O H:不客氣! –

+0

直覺上我會選擇正則表達式'\ * \ | [^ * |] + \ | \ *',即使用否定字符類。據我所知,結果將幾乎相同(您的正則表達式允許空標籤)。在否定的字符類中使用非貪婪的''是否有優勢? –