日期:2014-05-19  浏览次数:20758 次

C#下的一个字符串拆分问题
如何将字符串:

a[sdk]adf[2wse]opj[asdf]2wesa

拆分为

a
[sdk]
adf
[2wse]
opj
[asdf]
2wesa

如果用正则   希望给各思路   谢谢:)

------解决方案--------------------
protected void Page_Load(object sender, EventArgs e)
{
string testString = TextBox1.Text;
string[] result = testString.Split(new char[] { '[ ', '] ' });
Response.Write( "分解字串: <br> ");
int count = 0;
foreach (string rword in result)
{
if (count % 2 == 0&&rword.Length!=0)
{
Response.Write(rword + " <br> ");
}
else if(rword.Length!=0)
{
Response.Write( "[ " + rword + "] <br> ");
}
count++;
}
}

方法笨了點,可以湊合著用.
------解决方案--------------------
我的最简单,测试通过
string str = "a[sdk]adf[2wse]opj[asdf]2wesa ";
string[] arr = str.Split(new char[] { '[ ', '] '});
for(int i=1;i <arr.Length;i+=2)
{
arr[i] = '[ ' + arr[i] + '] ';
}
------解决方案--------------------
以为只有字母,那这个总行了吧

string yourStr = richTextBox1.Text;
MatchCollection mc = Regex.Matches(yourStr, @ "\[?[^\[\]]+\]? ");
foreach (Match m in mc)
{
 richTextBox2.Text += m.Value + "\n ";
}
------解决方案--------------------
Regex regex = new Regex(@ "(\[[^\[\]]+\]) ");