简体   繁体   English

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

[英]Regex formatting not working as expected

I have the following extension methods:我有以下扩展方法:

/*
* 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;
}

I'm calling the method with the following arguments:我正在使用以下参数调用该方法:

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

I would expect text to end up like this /index.aspx?xmlFilePath=MCicero_temppreview.xml , but instead I got /index.aspx?xmlFilePath= , as if the group didn't match the input.我希望text最终像这样/index.aspx?xmlFilePath=MCicero_temppreview.xml ,但我得到了/index.aspx?xmlFilePath= ,好像该组与输入不匹配。

I tried this regex and input in Regex101 , and it seems to work fine.我在Regex101 中尝试了这个正则表达式和输入,它似乎工作正常。

What may be going on here?这里可能发生了什么?

I think it is because you use ?我想是因为你用? in the end of your regex, and the first match is empty string, as ?在正则表达式的末尾,第一个匹配项是空字符串,如? means (after regex101 explanation):意味着(在 regex101 解释之后):

Between zero and one time, as many times as possible, giving back as needed在零到一次之间,尽可能多次,根据需要回馈

Even in your regex101 example, you need to use /g mode to capture groups, and with /g there are visible dotted lines between every character pairs, which means that regex matched there - because it always match.即使在您的 regex101 示例中,您也需要使用 /g 模式来捕获组,并且使用 /g 在每个字符对之间都有可见的虚线,这意味着正则表达式在那里匹配 - 因为它始终匹配。 So your function just returns, what it captured, empty string.所以你的函数只返回它捕获的空字符串。

So try with:所以尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM