gpt4 book ai didi

c# - 如何在正则表达式中留出空间?

转载 作者:行者123 更新时间:2023-11-30 23:31:19 24 4
gpt4 key购买 nike

我试图在 New : 双引号后获取值。当 ListName 中没有空格时,我可以很好地检索值。但是如果我在列表名称之间放置空格(例如 NewFinancial History:\"xyz\"),它会抛出以下错误:

parsing "NewFinancial History:"(?[^"]*)"" - Invalid group name: Group names must begin with a word character.

它在下一行抛出错误var matches = Regex.Matches(contents, regex, RegexOptions.Singleline);

下面是我的代码。

string contents = " testing NewFinancial History:\"xyz\"   ";
var keys = Regex.Matches(contents, @"New(.+?):", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace).OfType<Match>().Select(m => m.Groups[0].Value.Trim().Replace(":", "")).Distinct().ToArray();

foreach (string key in keys)
{
List<string> valueList = new List<string>();
string listNameKey = key;
string regex = "" + listNameKey + ":" + "\"(?<" + listNameKey + ">[^\"]*)\"";

var matches = Regex.Matches(contents, regex, RegexOptions.Singleline);
foreach (Match match in matches)
{
if (match.Success)
{
string value = match.Groups[key].Value;
valueList.Add(value);
}
}
}

最佳答案

我不明白你为什么还要使用“key”作为组名。

你的问题是组名不能包含空格,但您可以简单地创建一个匿名组。

string contents = " testing NewFinancial History:\"xyz\"   ";
var keys = Regex.Matches(contents, @"New(.+?):", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace).OfType<Match>().Select(m => m.Groups[0].Value.Trim().Replace(":", "")).Distinct().ToArray();

foreach (string key in keys)
{
List<string> valueList = new List<string>();
string listNameKey = key;
string regex = "" + listNameKey + ":" + "\"([^\"]*)\""; //create an anonymous capture group

var matches = Regex.Matches(contents, regex, RegexOptions.Singleline);
foreach (Match match in matches)
{
if (match.Success)
{
string value = match.Groups[0].Value; //get the first group
valueList.Add(value);
}
}
}

关于c# - 如何在正则表达式中留出空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34621606/

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