0

我有以下字符串:

(a,b,c,d,e)

我想通过正则表达式取出所有逗号分隔的值。

如果我收起括号

a,b,c,d,e

并使用以下正则表达式:

([^,]),?

对于每个逗号分隔值,我得到一个匹配项和一个组。

但是,如果我想使用正则表达式处理结束括号:

\((([^,]),?)+\)

我仍然只得到一场比赛和一组。该组仅包含最后一个逗号分隔值。

我还尝试了组捕获,例如:

(?:....)
(...?)
(...)?

但我无法通过正则表达式组取出逗号分隔值。

当逗号分隔值括在括号中时,我该怎么做?

4

2 回答 2

0

一般来说,这就是重复组的工作方式——你没有单独的组,只有最后一个。如果要在逗号之间分隔值,最好使用编程语言中可用的字符串函数来首先去除括号,然后在逗号上分割字符串。

例如在 Ruby 中:

 [10] pry(main)> '(a,b,c,d,e,f)'.gsub(/[()]/,'').split(',')
 # => ["a", "b", "c", "d", "e", "f"]
于 2018-03-13T11:50:52.013 回答
0

我发现了。使用 C#,您可以使用匹配集合中的属性 Captures。

使用正则表达式:

\((([^,]),?)+\)

做:

        string text = "(a,b,c,d,e)";
        Regex rgx = new Regex("\\((([^,]),?)+\\)");
        MatchCollection matches = rgx.Matches(text);

然后你在 matchcollection 中有 1 个包含以下 3 个组的项目:

[0]: \((([^,]),?)+\) => (a,b,c,d,e)
[1]: ([^,]),?+ => value and optional comma, eg. a, or b, or e
[2]: [^,] => value only, eg. a or b or ...

组内捕获的列表通过量化器存储每个提取的值。所以使用组 [2] 和捕获来获取所有值。

所以解决方案是:

        string text = "(a,b,c,d,e)";
        Regex rgx = new Regex("\\((([^,]),?)+\\)");
        MatchCollection matches = rgx.Matches(text);

        //now get out the captured calues
        CaptureCollection captures = matches[0].Groups[2].Captures;

        //and extract them to list
        List<string> values = new List<string>();
        foreach (Capture capture in captures)
        {
            values.Add(capture.Value);
        }
于 2018-03-15T08:37:44.863 回答