在c#中使用正则表达式拆分字符串

时间:2012-01-31 20:50:41

标签: regex

我有一个包含以下内容的文件

aaaaa(fasdfiojasdlfkj)
213.df(fasdfsadffdfsd)
53434534535(oipowerier)
2.3.*12.4(asdfrwer)

我想最终有一个这样的清单,

List<string[]> sList = new List<string[]>();
sList[0] = new string[]{"aaaaa", "fasdfiojasdlfkj"};
sList[1] = new string[]{"213.df", "fasdfsadffdfsd"};
sList[2] = new string[]{"53434534535", "oipowerier"};
sList[3] = new string[]{"2.3.*12.4", "asdfrwer"};

3 个答案:

答案 0 :(得分:3)

您不需要Regex - string.Split就够了。

如果你使用行:

List<string[]> sList = new List<string[]>();
foreach(var line in fileLines)
{
    sList.Add(line.Split(new Char[]{ '(', ')'}, 
              StringSplitOptions.RemoveEmptyEntries));
}

答案 1 :(得分:3)

您可以在没有正则表达式的情况下执行此操作:

var result = stringlist.ConvertAll(x =>x.Split(new char[] {'(',')'},
                           StringSplitOptions.RemoveEmptyEntries));

答案 2 :(得分:0)

List<string[]> sList = new List<string[]>();

MatchCollection matches = Regex.Matches(yourtext, @"([^\(]+)\(([^\)]+)\)");

foreach(Match mymatches in matches)
{

    //get the data
    string firststring = mymatches.Groups[1].Value;
    string secondstring = mymatches.Groups[2].Value;

    sList.Add(new string[] {firststring, secondstring});
}

虽未测试....