2012-10-30 46 views
0

我想從我的字符串匹配字符串,如<word>~,<word>~0.1,<word>~0.9正則表達式查找字符串C#

但它不應該匹配,如果它在雙引號如"<word>~0.5""<word>"~0.5

舉幾個例子:

"World Terror"~10 AND music~0.5    --> should match music~0.5 
"test~ my string"        --> should not match 
music~ AND "song remix" AND "world terror~0.5" --> should match music~ 

我已經申請下面的正則表達式現在\w+~,但如果比賽被包含引號內也一致。

可以請任何人幫助我嗎?

+0

您需要使用負向後視和前視。 Google他們。 – Barmar

+0

這很複雜。我假設你也不想匹配'「foo吧〜10 baz」',對嗎?那麼,它可以在正則表達式中完成,但是我想首先知道引用的字符串是否可以包含轉義引號(如'\「')? –

+0

@Barmar:對於不知道正則表達式,谷歌搜索不會幫他在這裏,StackOverflow可以 –

回答

2

這將字符串工作不包含轉義引號(因爲這些會拋出計數爲偶數的報價表外):

Regex regexObj = new Regex(
    @"\w+~[\d.]* # Match an alnum word, tilde, optional digits/dots 
    (?=   # only if there follows... 
    [^""]*  # any number of non-quotes 
    (?:   # followed by... 
     ""[^""]* # one quote, and any number of non-quotes 
     ""[^""]* # another quote, and any number of non-quotes 
    )*   # any number of times, ensuring an even number of quotes 
    [^""]*  # Then any number of non-quotes 
    $   # until the end of the string. 
    )    # End of lookahead assertion", 
    RegexOptions.IgnorePatternWhitespace); 

如果轉義引號需要解決的問題,它有點複雜:

Regex regexObj = new Regex(
    @"\w+~[\d.]*   # Match an alnum word, tilde, optional digits/dots 
    (?=     # only if there follows... 
    (?:\\.|[^\\""])* # any number of non-quotes (or escaped quotes) 
    (?:     # followed by... 
     ""(?:\\.|[^\\""])* # one quote, and any number of non-quotes 
     ""(?:\\.|[^\\""])* # another quote, and any number of non-quotes 
    )*     # any number of times, ensuring an even number of quotes 
    (?:\\.|[^\\""])* # Then any number of non-quotes 
    $     # until the end of the string. 
    )     # End of lookahead assertion", 
    RegexOptions.IgnorePatternWhitespace); 
+0

謝謝,我會檢查出來,並儘快回覆給你:) – meghana

+0

謝謝@Tim Pietzcker,我測試了你的第一個正則表達式,它正是我想要的。 :)。並再次感謝第二次正則表達式,我也會了解它。 :) – meghana

相關問題