首页 新闻 会员 周边

.NET如何字符串变为数组

0
悬赏园豆:5 [已解决问题] 解决于 2011-09-23 14:42

题目:string str="a[bc]def[ghi]jklmn"

变为如下形式:

a

bc

def

ghi

klmn

 

尽量不要使用split方法。

问题补充:

如果输出是这种形式:

a

[bc]

def

[ghi]

klmn

怎么做,跪求答案

walleyekneel的主页 walleyekneel | 菜鸟二级 | 园豆:306
提问于:2011-09-23 13:37
< >
分享
最佳答案
0

第一种输出形式:

string text = "a[bc]def[ghi]jklmn";
var regex = new Regex(@"(\w)\[(\w{2})\](\w{3})\[(\w{3})\](\w{5})");
var match = regex.Match(text);
string[] strArray = new string[match.Groups.Count-1];
for (int i = 1; i < match.Groups.Count; i++)
{
strArray[i-1] = match.Groups[i].Value;
}

第二种输出形式:

string text = "a[bc]def[ghi]jklmn";
var regex = new Regex(@"(\w)(\[\w{2}\])(\w{3})(\[\w{3}\])(\w{5})");
var match = regex.Match(text);
string[] strArray = new string[match.Groups.Count-1];
for (int i = 1; i < match.Groups.Count; i++)
{
strArray[i-1] = match.Groups[i].Value;
}

两段代码只是正则表达式稍有不同,将()移到了[]外面。


收获园豆:5
dudu | 高人七级 |园豆:30979 | 2011-09-23 14:30
其他回答(4)
0

这个貌似就只能用split 吧? 

string str = "a[bc]def[ghi]jklmn";
string[] temp = str.Split('[', ']');

这样不是挺简单的吗

Devin Mao | 园豆:596 (小虾三级) | 2011-09-23 13:56
0
            List<string> b = new List<string>();
string temp = "";
foreach (var o in test)
{
if (o != '[' && o != ']')
{
temp += o;
if (o == test[test.Length - 1])
{
b.Add(temp);
}
}
else
{
b.Add(temp);
temp = "";
}
}

b就是你要的

artwl | 园豆:16736 (专家六级) | 2011-09-23 13:56

如果有括号用:

            List<string> b = new List<string>();
string temp = "";
foreach (var o in test)
{
if (o != '[' && o != ']')
{
temp += o;
if (o == test[test.Length - 1])
{
b.Add(temp);
}
}
else
{
if (o == ']')
{
temp += o;
}
b.Add(temp);
temp = "";
if (o == '[')
{
temp = o + temp;
}
}
}

b就是带括号的

支持(0) 反对(0) artwl | 园豆:16736 (专家六级) | 2011-09-23 14:21

思路不错,有空我要跟你学习一下。。。但是不是我想要的结果,我想用正则表达式怎么匹配

支持(0) 反对(0) walleyekneel | 园豆:306 (菜鸟二级) | 2011-09-23 14:48
0

为什么不能用split方法?

顾晓北 | 园豆:10844 (专家六级) | 2011-09-23 14:09

split方法是我想出来,我只是想有没有其他好的方法。。可以学习一下

支持(0) 反对(0) walleyekneel | 园豆:306 (菜鸟二级) | 2011-09-23 14:48
0

跟二楼想法一致

Apple丫头 | 园豆:451 (菜鸟二级) | 2011-09-23 14:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册