在空白忽视paranthesis将字符串分割 [英] Split string on whitespace ignoring paranthesis
本文介绍了在空白忽视paranthesis将字符串分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,如本
(ed) (Karlsruhe Univ. (TH) (Germany, F.R.))
我需要把它分成两个像这样
I need to split it into two such as this
ed
Karlsruhe Univ. (TH) (Germany, F.R.)
基本上,paranthesis中忽略空格和paranthesis
Basically, ignoring whitespace and paranthesis within a paranthesis
是否有可能使用正则表达式,如果你能做到这一点?
Is it possible to use a regex to achieve this?
推荐答案
有更多的括号,这是更好地使用均衡组:
If you can have more parentheses, it's better to use balancing groups:
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);
}
的 ideone演示
分析:
\(( # 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
这篇关于在空白忽视paranthesis将字符串分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文