[英]Regular Expression to split a string with parentheses
需要RegEx幫助。 使用C#。
括號中的一組單詞(圓形,方框或卷曲)應視為一個單詞。 括號外的部分應基於空格''分割。
A)測試用例–
輸入- Andrew. (The Great Musician) John Smith-Lt.Gen3rd
Andrew. (The Great Musician) John Smith-Lt.Gen3rd
結果(字符串數組)–
1.安德魯。
2.偉大的音樂家
3.約翰
4. Smith-Lt.Gen3rd
B)測試用例–
輸入- Andrew. John
Andrew. John
結果(字符串數組)–
1.安德魯。
2.約翰
C)測試用例–
輸入- Andrew {The Great} Pirate
結果(字符串數組)–
1.安德魯
2.偉大的
3.海盜
輸入的是個人或任何其他實體的名稱。 當前系統是用Access寫的很舊的系統。 他們通過逐個字符地掃描來做到這一點。 我將其替換為C#。
我想分兩個步驟進行操作-首先是基於括號的拆分,然后是單詞拆分。
我想把這些案件作為不好的輸入-
僅起始或結束括號可用
嵌套括號
總的來說,我只想分割格式正確的輸入(如果有起始括號,則必須有結尾)。
這是一個正則表達式,它將為您的示例提供正確的結果:
\s(?=.*?(?:\(|\{|\[).*?(?:\]|\}|\)).*?)|(?<=(?:\(|\[|\{).*?(?:\}|\]|\)).*?)\s
此正則表達式分為兩部分,中間用|
分隔|
(OR)陳述:
\\s(?=.*?(?:\\(|\\{|\\[).*?(?:\\]|\\}|\\)).*?)
-在()
組之前尋找空白, []
或{}
(?<=(?:\\(|\\[|\\{).*?(?:\\}|\\]|\\)).*?)\\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部分是相同的東西,但是它具有先行( (?<=)
)而不是先行( (?=)
(?<=)
)
之后的問題由作者編輯:
對於僅搜索帶有完整括號的行的正則表達式,可以使用以下命令:
.*\\(.*(?=.*?\\).*?)|(?<=.*?\\(.*?).*\\).*
您可以使用它用{
和}
或[
和]
替換(
和)
,以便使用完整的花括號和方括號。
這個怎么樣:
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);
假定沒有嵌套的括號/括號/括號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.