从定义的分隔符到字符串数组之间的字符串提取所有子字符串
问题描述:
我需要某种方法,使用正则表达式或拆分我不知道以下内容。从定义的分隔符到字符串数组之间的字符串提取所有子字符串
我有串,看起来像这样:
ls 0
[0,86,180]
ls 1
[1,2,200]
ls 2
[2,3,180]
ls 3
[3,4,234]
...等等。我希望括号[]之间的所有内容都是字符串数组中的一个字符串,其他所有内容都可以忽略。
答
这可能给你的整体思路和步骤:
var yourString = @"ls 0
[0,86,180]
ls 1
[1,2,200]
ls 2
[2,3,180]
ls 3
[3,4,234]";
var result = yourString.Split(new char[] { '\n' }) //split
.Where(i => i.Contains('[')) //filter
.Select(i => i.Replace("[", string.Empty) //prepare
.Replace("]", string.Empty))
.ToList();
var newArray = string.Join(",", result); //merge the result
答
如果块数并不总是套三分球
var myString = "ls 0
[0,86,180]
ls 1
[1,2,200]
ls 2
[2,3,180]
ls 3
[3,4,234]";
RegEx pattern = new RegEx(@"\[[\d,]*\]*");
Match numbers = pattern.Match(myString);
if(numbers.Success)
{
do {
var val = numbers.Value;
// code for each block of numbers
numbers.NextMatch();
} while(numbers.Success)
}
的[我如何提取文本谎言
可能重复在圆括号(圆括号)之间?](http://stackoverflow.com/questions/378415/how-do-i-extract-text-that-lies-between-parentheses-round-brackets) –