c# - 正则表达式格式无法按预期工作

标签 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("{{{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 解释之后):

Between zero and one time, as many times as possible, giving back as needed

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

所以试试:

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

关于c# - 正则表达式格式无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31248926/

相关文章:

php - 通过正则表达式查找字符串中的十进制数

python - 使用正则表达式 python 替换

regex - Angular 7 中的模式验证

Django翻译和gettext : The deprecation of the % (string interpolation) operator

c# - 透明键失效怎么办?

c# - 为什么 *p++ = *p - a 会给出奇怪的结果?

c# - 是否可以编译使用 .NET DLL 和 GCC 的 C++?

c# - 如何将此 HipChat curl 帖子转换为 C#?

c# - textBox1.Text.Insert(...) 方法不起作用

php - 将 url 与字符串分开?