2013-03-11 284 views
1

需要RegEx幫助。使用C#。使用括號分割字符串的正則表達式

圓括號中的單詞組(圓形或方框或捲曲)應視爲一個單詞。該部分位於括號外,應根據空格「'進行分割。

A)測試用例 -

輸入 - Andrew. (The Great Musician) John Smith-Lt.Gen3rd

結果字符串(數組) -
安德魯。
2.偉大的音樂家
約翰
4.史密斯Lt.Gen3rd

B)測試案例 -

輸入 - Andrew. John

結果字符串(數組) -
安德魯。
2.約翰

C)測試用例 -

輸入 - Andrew {The Great} Pirate

結果字符串(數組) -
安德魯
2.大
3.海盜

輸入是一個人或任何其他實體的名稱。目前的系統是非常古老的寫在Access中。他們通過逐字掃描來完成它。我用C#替換它。

我認爲這樣做分兩步 - 第一個圓括號拆分,然後分詞。

我想扔這種情況下出壞輸入 -

  1. 只有起點或終點可用括號

  2. 嵌套的括號

總體來說,我想拆分僅好形成(如果開始括號存在,則必須有結尾)僅限輸入。

+0

由於圓括號可以嵌套,正則表達式是該作業的錯誤工具。你必須寫一個解析器。 – 2013-03-11 21:22:21

+0

這並非完全正確。根據輸入,如果你知道相同類型的花括號不會被嵌套,那麼你很好。 – FrankieTheKneeMan 2013-03-11 21:22:56

+0

'「和{什麼(關於字符串)喜歡)?」' – 2013-03-11 21:24:41

回答

1

如何:

Regex regexObj = new Regex(
    @"(?<=\()  # Assert that the previous character is a (
    [^(){}[\]]+  # Match one or more non-paren/brace/bracket characters 
    (?=\))   # Assert that the next character is a) 
    |    # or 
    (?<=\{)[^(){}[\]]+(?=\}) # Match {...} 
    |    # or 
    (?<=\[)[^(){}[\]]+(?=\]) # Match [...] 
    |    # or 
    [^(){}[\]\s]+ # Match anything except whitespace or parens/braces/brackets", 
    RegexOptions.IgnorePatternWhitespace); 

這不承擔任何嵌套的括號/括號/括號。

3

這裏是一個正則表達式,將給予正確的結果,從你的例子:

\s(?=.*?(?:\(|\{|\[).*?(?:\]|\}|\)).*?)|(?<=(?:\(|\[|\{).*?(?:\}|\]|\)).*?)\s 

這正則表達式是兩個部分,由|(OR)語句分開:

  1. \s(?=.*?(?:\(|\{|\[).*?(?:\]|\}|\)).*?) - 查找對於前面的空白區域設置(),[]{}
  2. (?<=(?:\(|\[|\{).*?(?:\}|\]|\)).*?)\s - 在設置後尋找空白,[],或{}

這裏是各部分的擊穿:

第1部分(\s(?=.*?(?:\(|\{|\[).*?(?:\]|\}|\)).*?)):

1. \s    - matches white space 
2. (?=   - Begins a lookahead assertion (What is included must exist after the \s 
3. .*?   - Looks for any character any number of times. The `?` makes in ungreedy, so it will grab the least number it needs 
4. (?:\(|\{|\[) - A non passive group looking for `(`, `{`, or `[` 
5. .*?   - Same as #3 
6. (?:\]|\}|\)) - The reverse of #4 
7. .*?   - Same as #3 
8.)    - Closes the lookahead. #3 through #7 are in the lookahead. 

第2部分是同樣的事情,但不是先行( (?=))它有一個看起來((?<=)

後問題編輯作者:

對於一個正則表達式,將與唯一完整的括號線搜索,您可以使用此:

.*\(.*(?=.*?\).*?)|(?<=.*?\(.*?).*\).*

你可以用它與{}[],所以你不得不更換()完整的捲曲和方括號。

相關問題