在 C# 中拆分字符串 [英] Splitting a string in C#

查看:30
本文介绍了在 C# 中拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按以下方式在 C# 中拆分字符串:

I am trying to split a string in C# the following way:

传入字符串的形式为

string str = "[message details in here][another message here]/n/n[anothermessage here]"

我试图将其拆分为表单中的字符串数组

And I am trying to split it into an array of strings in the form

string[0] = "[message details in here]"
string[1] = "[another message here]"
string[2] = "[anothermessage here]"

我试图以这样的方式做到这一点

I was trying to do it in a way such as this

string[] split =  Regex.Split(str, @"[[^[]+]");

但是这种方式不能正常工作,我只是得到一个空数组或字符串

But it does not work correctly this way, I am just getting an empty array or strings

任何帮助将不胜感激!

推荐答案

改用 Regex.Matches 方法:

string[] result =
  Regex.Matches(str, @"[.*?]").Cast<Match>().Select(m => m.Value).ToArray();

这篇关于在 C# 中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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