通过括号中的逗号分组串 [英] Grouping string by comma between brackets

查看:89
本文介绍了通过括号中的逗号分组串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回应: HTTP: //stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclud



我正在寻找一个适用于我的字符串,包括括号中的正则表达式:

Response to : http://stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclud

Hi,I'm looking for a regex pattern that applies to my string including brackets:

[1,2,3, 4,5] [ABC,EF,G] [0,2,4b,Y7]

可以是任何东西,包括文字,数字,非字一起或分开。

[1,2,3,4,5] [abc,ef,g] [0,2,4b,y7]
could be anything including word,digit,non-word together or separated.

我想用 \ [(。*?)\]
,但是那是什么会给我用逗号分隔支架和子组字符串之间的小组,这样的结果可能是以下??

I wish to get the group between brackets by \[(.*?)\] but what is the regex pattern that will give me the group between brackets and sub-group strings separated by commas so that the result may be following ??


Group1 : 1,2,3,4,5
 Group1: 1
 Group2: 2
 Group3: 3
 Group4: 4
 Group5: 5

Group2 : abc,ef,g
 Group1: abc
 Group2: ef
 Group3: g

etc ..

感谢您的帮助。

推荐答案

我同意@Dav,你会在每个方括号组使用String.Split是最好的。

I agree with @Dav that you would be best using String.Split on each square-bracketed group.

不过,可以提取使用数据单正则表达式:

However, you can extract all the data using a single regular expression:

(?:\s*\[((.*?)(?:,(.+?))*)\])+

使用这个表达式,你必须处理所有每个捕获来获取所有数据。作为一个例子,在你的字符串运行下面的代码:

Using this expression, you will have to process all the captures of each group to get all the data. As an example, run the following code on your string:

var regex = new Regex(@"(?:\s*\[((.*?)(?:,(.+?))*)\])+");
var match = regex.Match(@"[1,2,3,4,5] [abc,ef,g] [0,2,4b,y7]");

for (var i = 1; i < match.Groups.Count; i++)
{
    var group = match.Groups[i];
    Console.WriteLine("Group " + i);

    for (var j = 0; j < group.Captures.Count; j++)
    {
        var capture = group.Captures[j];

        Console.WriteLine("  Capture " + j + ": " + capture.Value 
                                       + " at " + capture.Index);
    }
}

这将产生以下的输出:


Group 1
  Capture 0: 1,2,3,4,5 at 1
  Capture 1: abc,ef,g at 13
  Capture 2: 0,2,4b,y7 at 24
Group 2
  Capture 0: 1 at 1
  Capture 1: abc at 13
  Capture 2: 0 at 24
Group 3
  Capture 0: 2 at 3
  Capture 1: 3 at 5
  Capture 2: 4 at 7
  Capture 3: 5 at 9
  Capture 4: ef at 17
  Capture 5: g at 20
  Capture 6: 2 at 26
  Capture 7: 4b at 28
  Capture 8: y7 at 31

1组为您提供了每个方括号组的值,2组为您提供了每个方括号组与组相匹配的第一个项目3给你所有的后续项目。你将不得不看捕获的指标,以确定哪些项目属于每个方括号组。

Group 1 gives you the value of each square-bracketed group, group 2 gives you the first item matched in each square-bracketed group and group 3 gives you all the subsequent items. You will have to look at the indexes of the captures to determine which item belongs to each square-bracketed group.

这篇关于通过括号中的逗号分组串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆