[英]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.