我想拆分以下内容:
name[]address[I]dob[]nationality[]occupation[]
所以我的结果是:
name[]
address[I]
dob[]
nationality[]
occupation[]
我尝试使用Regex.Split
但无法获得这些结果。
答案 0 :(得分:0)
使用此正则表达式模式:
\w*\[\w*\]
答案 1 :(得分:0)
正则表达式应该没问题。您还可以考虑使用string.IndexOf捕获开始和结束方括号,例如:
IEnumerable<string> Results(string input)
{
int currentIndex = -1;
while (true)
{
currentIndex++;
int openingBracketIndex = input.IndexOf("[", currentIndex);
int closingBracketIndex = input.IndexOf("]", currentIndex);
if (openingBracketIndex == -1 || closingBracketIndex == -1)
yield break;
yield return input.Substring(currentIndex, closingBracketIndex - currentIndex + 1);
currentIndex = closingBracketIndex;
}
}
答案 2 :(得分:0)
string inputString = "name[]address[I]dob[]nationality[]occupation[]";
var result = Regex.Matches(inputString, @".*?\[I?\]").Cast<Match>().Select(m => m.Groups[0].Value).ToArray();