简体   繁体   中英

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.

I tried this regex and input in Regex101 , and it seems to work fine.

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):

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. So your function just returns, what it captured, empty string.

So try with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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