gpt4 book ai didi

c# - "Tight"重复键/值匹配

转载 作者:行者123 更新时间:2023-11-30 14:22:25 26 4
gpt4 key购买 nike

具有键/值对“紧密”重复模式的字符串(对于此示例,键是“name”,值应该是单个小写单词)

string text = "name: abc name: def name: ghi name: jkl";

应该转化为输出

abc, def, ghi, jkl,

而模式中的任何干扰(可以说是“非紧”)

string text = "name: abc x name: def name: ghi name: jkl";

应该会导致匹配失败,类似于

abc, ## Exception occurred: x cannot be matched to the pattern ##

我试过了

string text = "name: abc name: def name: ghi name: jkl";
string pattern = @"name:\s*([a-z])*\s*";

MatchCollection ms = Regex.Matches(text, pattern);

foreach (Match m in ms)
{
Console.Write(m.Groups[1].Value+", ");
}

但它返回

c, f, i, l,

是什么导致了这种奇怪的行为,我该如何解决?

最佳答案

您只需将 * 移到括号内即可捕获完整字符串。如果你想防止无效输入,那么正则表达式并不是绝对必要的。这假设您的值不能有空格,因为这将是一个更难解决的问题。

void Main()
{
string validText = "name: abc name: def name: ghi name: jkl";
string invalidText = "name: abc x name: def name: ghi name: jkl";
string validPattern = @"name:\s*([a-z]*)\s*";

if (!Validate(invalidText))
{
try
{
throw new Exception("invalid input");
}
catch (Exception exception)
{
Console.WriteLine($"Input '{invalidText}' produces: {exception.Message}");
}
}

MatchCollection ms = Regex.Matches(validText, validPattern);

Console.Write($"Input '{validText}' produces: ");
foreach (Match m in ms)
{
Console.Write(m.Groups[1].Value + ", ");
}
}

public static bool Validate(string input)
{
var pairs = input.Split(' ');
return !pairs.Where((item, index) => index % 2 != 0).Any(item => item.EndsWith(":"));
}

// Input 'name: abc x name: def name: ghi name: jkl' produces: invalid input
// Input 'name: abc name: def name: ghi name: jkl' produces: abc, def, ghi, jkl,

https://regex101.com/r/qsQNr1/1

关于c# - "Tight"重复键/值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49799840/

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