正则表达式格式不能按预期工作

时间:2015-07-06 14:49:19

标签: c# regex string format

我有以下扩展方法:

/*
* 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("{error}", 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尝试了这个正则表达式和输入,似乎工作正常。

这里可能会发生什么?

1 个答案:

答案 0 :(得分:1)

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

  

在零到一次之间,尽可能多次回馈   需要

即使在你的regex101例子中,你需要使用/ g模式来捕获组,并且/ g在每个字符对之间都有可见的虚线,这意味着正则表达式在那里匹配 - 因为它始终匹配。所以你的函数只返回它捕获的内容,空字符串。

请尝试:

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