Regex格式没有按预期工作

本文关键字:工作 格式 Regex | 更新日期: 2023-09-27 18:01:24

我有以下扩展方法:

/*
* text.Format("hello", "no") --> Replaces all appearances of "{hello}" with "no"
*
* For example, if text would have been "{hello} how are you?", the method would have returned "no how are you?"
*/
public static StringBuilder CustomFormat(this StringBuilder text, string name, string value)
{
     return text.Replace(String.Format("{{{0}}}", name), value);
}
/*
*  text.FormatUsingRegex("(?'hello'[A-Z][a-z]{3})", "Mamma mia") --> Replaces the text with the found matching group in the input
*
* For example if text would have been "{hello}oth", the method would have returned "Mammoth"
*/
public static StringBuilder FormatUsingRegex(this StringBuilder text, string regexString, string input)
{
     Regex regex = new Regex(regexString);
     List<string> groupNames = regex.GetGroupNames().ToList();
     Match match = regex.Match(input);
     groupNames.ForEach(groupName => text.CustomFormat(groupName, match.Groups[groupName].Value));
     return text;
}

我用以下参数调用方法:

 StringBuilder text = new StringBuilder("/index.aspx?xmlFilePath={xmlFilePath}");
 text.FormatUsingRegex("(f=(?'xmlFilePath'.*))?","http://localhost:24674/preview/f=MCicero_temppreview.xml");

我希望text最终会像/index.aspx?xmlFilePath=MCicero_temppreview.xml一样,但我得到了/index.aspx?xmlFilePath=,好像组与输入不匹配。

我在Regex101中尝试了这个正则表达式和输入,它似乎工作得很好。

这里可能发生了什么?

Regex格式没有按预期工作

我认为这是因为您在正则表达式的末尾使用?,并且第一个匹配是空字符串,因为?意味着(在regex101解释之后):

在0到1之间,尽可能多地回馈需要

即使在regex101示例中,您也需要使用/g模式来捕获组,并且在/g中,每个字符对之间都有可见的虚线,这意味着regex在那里匹配—因为它总是匹配的。所以你的函数只是返回,它捕获的,空字符串。

所以试试输入:

(f=(?'xmlFilePath'.*))