gpt4 book ai didi

c# - 获取除方括号内的正斜杠

转载 作者:太空狗 更新时间:2023-10-29 23:25:14 25 4
gpt4 key购买 nike

示例文本(我已经突出显示了所需的 /):

对[@Key=2]/项目/项目[Person/Name='Martin']/日期

我正在尝试获取不在方括号内的每个正斜杠,任何精通 Regex 的人都可以帮助我解决这个问题吗?用途是:

string[] result = Regex.Split(text, pattern);

我已经用这段代码完成了,但想知道是否有一个更简单的 Regex 可以做同样的事情:

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();
}

最佳答案

使用 Regex.Matches 可能是比尝试使用拆分更好的方法。您无需指定要拆分的模式,而是尝试匹配所需的输出。这适用于基本情况:

string[] FancySplit(string input) {
return Regex.Matches(input, @"([^/\[\]]|\[[^]]*\])+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
}

正则表达式的方法是查找以下序列:

  • 不是[]/ 的字符
  • [ something ] 形式的序列,其中 something 允许包含 /

关于c# - 获取除方括号内的正斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10556282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com