[英]Regex formatting not working as expected
我有以下扩展方法:
/*
* 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 在每个字符对之间都有可见的虚线,这意味着正则表达式在那里匹配 - 因为它始终匹配。 所以你的函数只返回它捕获的空字符串。
所以尝试:
(f=(?'xmlFilePath'.*))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.