我有一个这样的字符串:
string test = "1Hello World 2I'm a newbie 33The sun is big 176The cat is black";
我想拆分字符串并放入如下数组:
1 Hello World
2 I'm a newbie
33 The sun is big
176 The cat is black
结果可能在String [],ArrayList,List或Linq
中添加了我尝试但不起作用的内容..
ArrayList oArrayList = new ArrayList();
Regex oRegex = new Regex(@"\d+");
Match oMatch = oRegex.Match(test);
int last = 0;
while (oRegex.Match(test).Success)
{
oArrayList.Add(oMatch.Value + " " + test.Substring(last, oMatch.Index));
last = oMatch.Index;
test = test.Remove(0, oMatch.Index);
oMatch = oRegex.Match(test);
}
答案 0 :(得分:0)
试试这个:
string test = "1Hello World 2I'm a newbie 33The sun is big 176The cat is black";
Regex regexObj = new Regex(@"(\d+)([^0-9]+)", RegexOptions.IgnoreCase);
Match match = regexObj.Match(test);
while (match.Success)
{
string numPart = match.Group[1].Value;
string strPart = match.Group[2].Value;
match = match.NextMatch();
}
输出:
答案 1 :(得分:0)
说实话很简单
string test = "1Hello World 2I'm a newbie 33The sun is big 176The cat is black";
var tmp = Regex.Split(test,@"\s(?=\d)");
tmp将是一个字符串数组
答案 2 :(得分:0)
给定输入字符串test
,您可以使用Regex.Split
拆分小数点边界上的字符串。在每个元素的数字和文本之间添加空格需要在每个元素上调用Regex.Match
以获得所需的格式:
var r = Regex.Split(test, @"(?<=\D)(?=\d)") // split at each boundary
// between a non-digit (\D)
// and digit (\d).
.Select(a=>Regex.Match(a, @"(\d+)(.*)").Result("$1 $2"));
// ^ insert a space between
// decimal and following text
结果是IEnumerable<string>
,可以在Linq中根据需要进行处理。