示例文本(我突出显示了所需/的文本):
对[@ Key = 2] /项目/项目[人/姓名='马丁'] /日期
我试图让每个正斜线都不在方括号内,任何人都可以帮助我解决这个问题吗?用途是:
string[] result = Regex.Split(text, pattern);
Run Code Online (Sandbox Code Playgroud)
我已经用这段代码完成了它,但是想知道是否有一个更简单的正则表达式可以做同样的事情:
private string[] Split()
{
List<string> list = new List<string>();
int pos = 0, i = 0;
bool within = false;
Func<string> add = () => Format.Substring(pos, i - pos);
//string a;
for (; i < Format.Length; i++)
{
//a = add();
char c = Format[i];
switch (c)
{
case '/':
if (!within)
{
list.Add(add());
pos = i + 1;
}
break;
case '[':
within = true;
break;
case ']':
within = false;
break;
}
}
list.Add(add());
return list.Where(s => !string.IsNullOrEmpty(s)).ToArray();
}
Run Code Online (Sandbox Code Playgroud)
使用Regex.Matches可能是比尝试使用 split 更好的方法。您无需指定要分割的模式,而是尝试匹配所需的输出。这适用于基本情况:
string[] FancySplit(string input) {
return Regex.Matches(input, @"([^/\[\]]|\[[^]]*\])+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
正则表达式的方法是查找以下序列:
[、]、 或/
[Something的序列],其中允许包含 Something/| 归档时间: |
|
| 查看次数: |
857 次 |
| 最近记录: |