我有以下扩展方法:
/*
* 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中输入,它似乎工作正常。
这可能是怎么回事?
最佳答案
我认为这是因为您在正则表达式的末尾使用了?
,并且第一个匹配项是空字符串,因为?
表示(在regex101解释之后):
在零到一遍之间,尽可能多地回馈
需要
即使在您的regex101示例中,您也需要使用/ g模式捕获组,并且/ g在每个字符对之间都有可见的虚线,这意味着regex在那里匹配-因为它始终匹配。因此,您的函数只是返回其捕获的空字符串。
因此,尝试:
(f=(?'xmlFilePath'.*))