대괄호를 제외하고 문자열을 부분 문자열로 분할
Nov 18 2020
다음을 "and"로 어떻게 나눌 수 있습니까?
field = "a > b and b = 0 and (f = 1 and g = 2)"
그러면 field.Split(" and ")
4 개의 문자열이 반환되며 그 안에 괄호가 있습니다.
a > b
b = 0
(f = 1
g = 2)
나는 외부 "and"로 분할하는 3 개의 문자열을 원한다.
a > b
b = 0
(f = 1 and g = 2)
다양한 Regex 옵션도 시도했지만 운이 없었습니다.
답변
5 WiktorStribiżew Nov 18 2020 at 20:07
중첩 된 균형 잡힌 괄호가 있더라도 다음을 사용할 수 있습니다.
\s*\band\b\s* # whole word and enclosed with 0+ whitespaces
(?= # start of a positive lookahead:
(?:
[^()]* # 0 or more chars other than ( and )
\((?>[^()]+|(?<o>\()|(?<-o>\)))*(?(o)(?!))\) # a (...) substring with nested parens support
)* # repeat the sequence of above two patterns 0 or more times
[^()]*$ # 0 or more chars other than ( and ) and end of string
) # end of the positive lookahead
regex 데모를 참조하십시오 .
C # 스 니펫 참조 :
var text = "a > b and b = 0 and (f = 1 and (g = 2 and j = 68) and v = 566) and a > b and b = 0 and (f = 1 and g = 2)";
var pattern = @"(?x)
var pattern = @"(?x)
\s*\band\b\s* # whole word and enclosed with 0+ whitespaces
(?= # start of a positive lookahead:
(?:
[^()]* # 0 or more chars other than ( and )
\((?>[^()]+|(?<o>\()|(?<-o>\)))*(?(o)(?!))\) # a (...) substring with nested parens support
)* # repeat the sequence of above two patterns 0 or more times
[^()]*$ # 0 or more chars other than ( and ) and end of string
) # end of the positive lookahead";
var results = Regex.Split(text, pattern);
산출:
a > b
b = 0
(f = 1 and (g = 2 and j = 68) and v = 566)
a > b
b = 0
(f = 1 and g = 2)