2011-08-10 223 views
10

如果不包含方括號,我必須解析文本,其中是關鍵字。我必須將關鍵字相匹配。此外,在的兩邊都必須有字邊界。正則表達式匹配不包圍括號的字符串

下面是一些例子,其中不是關鍵字:

  • [與]
  • [與]
  • [sometext與sometext]
  • [sometext與]
  • [with sometext]

下面是一些例子,其中 IS關鍵字

  • ]與
  • 你好與
  • 你好與世界
  • 你好[世界]與喂
  • 你好[世界]跟你好[世界]

無論如何他的LP? 在此先感謝。

回答

17

你可以查找單詞with,看到最接近支架的左側是不是一個開放支架,而最接近的支架其右側是不是一個右括號:

Regex regexObj = new Regex(
    @"(?<!  # Assert that we can't match this before the current position: 
    \[  # An opening bracket 
    [^[\]]* # followed by any other characters except brackets. 
    )   # End of lookbehind. 
    \bwith\b # Match ""with"". 
    (?!  # Assert that we can't match this after the current position: 
    [^[\]]* # Any text except brackets 
    \]  # followed by a closing bracket. 
    )   # End of lookahead.", 
    RegexOptions.IgnorePatternWhitespace); 
Match matchResults = regexObj.Match(subjectString); 
while (matchResults.Success) { 
    // matched text: matchResults.Value 
    // match start: matchResults.Index 
    // match length: matchResults.Length 
    matchResults = matchResults.NextMatch(); 
} 

的周圍的表情並不止於換行;如果您希望單獨評估每條生產線,請使用[^[\]\r\n]*而不是[^[\]]*

+0

@Tim:你的解決方案真的幫了我很多。現在我有類似的問題,只是,括號將被替換爲引號。我的意思是''有一些文字的文字「'不是關鍵字。我試圖用引號替換括號,但它不起作用。在Regex中我真的很糟糕,我需要你的幫助。謝謝:) – Mohayemin

+0

@Mohaimin,看看[這個問題](http://stackoverflow.com/questions/6111749/replace-whitespace-outside-quotes-using-regular-expression/6112179#6112179)這是一個非常相似問題;只需用'\ bwith \ b'替換正則表達式中的'[\]'部分,你應該很好走。 –

+0

@Tim:謝謝,那很完美。我只需要稍作修改,因爲我必須將引用正則表達式與上面給出的正則表達式合併。它工作得很好:D – Mohayemin

0

你會想看看負面的後視和負面的前瞻,這將幫助你匹配你的數據,而不消耗括號。

3

不錯的問題。我認爲找到適用於您的[with]模式的匹配會比較容易,然後反轉結果。

您需要匹配[,後面沒有],接着with(然後用於閉合方括號的相應圖案)

選配[with是容易的。

\[with 

添加先行排除],並且還允許任何數目的其它字符(.*

\[(?!]).*with 

那麼相應的關閉方括號,即具有反向預搜索相反。

\[(?!]).*with.*\](?<1[) 

多一點調整

\[(?!(.*\].*with)).*with.*\](?<!(with.*\[.*)) 

,現在如果你反了,你應該有你想要的結果。 (即,當這返回'真',你的模式匹配,並希望排除這些結果)。

1

我認爲最簡單的解決方案是搶先匹配平衡的括號及其內容對,以便在您搜索關鍵字時將它們排除在外。這裏是一個例子:

string s = 
    @"[with0] 
    [ with0 ] 
    [sometext with0 sometext] 
    [sometext with0] 
    [with0 sometext] 


    with1 
    ] with1 
    hello with1 
    hello with1 world 
    hello [ world] with1 hello 
    hello [ world] with1 hello [world]"; 

Regex r = new Regex(@"\[[^][]*\]|(?<KEYWORD>\bwith\d\b)"); 
foreach (Match m in r.Matches(s)) 
{ 
    if (m.Groups["KEYWORD"].Success) 
    { 
    Console.WriteLine(m.Value); 
    } 
} 
+0

Upvoting這個,不錯的一個艾倫。 :)不管你信不信,我只看到了其他三個使用這種技術的問題,儘管看到了許多類似的問題。 – zx81