具有多个括号的子串的正则表达式

时间:2015-12-25 10:21:22

标签: c# regex

尝试将字符串与键(值)模式中的多个括号匹配。

字符串1:

hostportservice(192.168.1.241(10001), service(master))   hostportservice(192.168.1.200(10001), service(slave))

String 1匹配

hostportservice(192.168.1.241(10001), service(master))
hostportservice(192.168.1.200(10001), service(slave))

字符串2:

hostportservice(192.168.1.241(10001), service(master))   updatedate(24-DEC-2015) updatetime(11:32:57 PM)

String 2 Matches

hostportservice(192.168.1.241(10001), service(master))
updatedate(24-DEC-2015)
updatetime(11:32:57 PM)

3 个答案:

答案 0 :(得分:1)

我认为RegEx不是解决这个问题的正确方法,因此可以更容易地解决这个问题。在C#中,这意味着遍历字符串,计算每次paranthesis计数为0时的parantheses和splitting,并且你命中了一个空格。

答案 1 :(得分:1)

有点复杂:

([^\s]+\s[^\s]+)\s+([^\s]+)\s+([^\s]+\s[^\s]+)|([^\s]+\s[^\s]+)\s+([^\s]+\s[^\s]+)

在这里演示:https://regex101.com/r/jP9uO0/1

答案 2 :(得分:0)

您尝试实现的目标是使用.NET Regex中的Balancing组完成的。您应该阅读以下链接

以下是适合您案例的代码。您可能需要使用它来使其适用于您的所有情况。

var pattern = new Regex(
                    @"\s*(?'TXT'(?:" +               /* Let's capture this expression */
                        @"[^()]*" +                  /* Part before parens start */
                        @"(?:(?'OPEN'\()[^()]*)+" +  /* Capture open paren followed by any text */
                        @"(?'-OPEN'\))+" +           /* Now remove the captured open paren group for every closed paren */
                    @")+?)" +                        /* Finished capture group */
                    @"(?(OPEN)(?!))"                 /* Confirm that no extra open parens are left on the stack */
                    );
var inputString = 
        @"hostportservice(192.168.1.241(10001), service(master))   hostportservice(192.168.1.200(10001), service(slave))" + Environment.NewLine +
        @"hostportservice(192.168.1.241(10001), service(master))   updatedate(24-DEC-2015) updatetime(11:32:57 PM)";

Match match;
int startAt = 0;
while ((match = pattern.Match(inputString, startAt)).Success) {
    Debug.WriteLine("Pattern Matched: " + match.Groups["TXT"].Value);
    startAt = match.Index + match.Length;
}