![](/img/trans.png)
[英]Regular expression help - ignoring parenthesis, ands, ors and whitespace
[英]Split string on whitespace ignoring parenthesis
我有這樣的字符串
(ed) (Karlsruhe Univ. (TH) (Germany, F.R.))
我需要將它分成兩個這樣
ed
Karlsruhe Univ. (TH) (Germany, F.R.)
基本上,忽略括號內的空格和括號
是否可以使用正則表達式來實現這一目標?
如果可以有更多的括號,則最好使用平衡組:
string text = "(ed) (Karlsruhe Univ. (TH) (Germany, F.R.))";
var charSetOccurences = new Regex(@"\(((?:[^()]|(?<o>\()|(?<-o>\)))+(?(o)(?!)))\)");
var charSetMatches = charSetOccurences.Matches(text);
foreach (Match match in charSetMatches)
{
Console.WriteLine(match.Groups[1].Value);
}
分解:
\(( # First '(' and begin capture
(?:
[^()] # Match all non-parens
|
(?<o> \( ) # Match '(', and capture into 'o'
|
(?<-o> \) ) # Match ')', and delete the 'o' capture
)+
(?(o)(?!)) # Fails if 'o' stack isn't empty
)\) # Close capture and last opening brace
\((.*?)\)\s*\((.*)\)
您將在兩個匹配組\\ 1和\\ 2中獲得兩個值
演示在這里: http : //regex101.com/r/rP5kG2
這就是您搜索並替換為\\1\\n\\2
,這似乎也正是您所需要的
string str = "(ed) (Karlsruhe Univ. (TH) (Germany, F.R.))";
Regex re = new Regex(@"\((.*?)\)\s*\((.*)\)");
Match match = re.Match(str);
一般來說,沒有
您不能在正則表達式中描述遞歸模式。 (由於不可能用有限的自動機識別它。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.