Это должно сделать это:
string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
string pattern = @"%(\d+(\.\d+)?)?(d|f|s)";
foreach (Match m in Regex.Matches(input, pattern))
{
Console.WriteLine(m.Value);
}
Я не использовал [dfs]
в своем шаблоне, так как планировал обновить его для использования именованных групп. Это основано на вашем предыдущем вопросе о поиске стратегии замены строк формата в стиле C.
Вот идея:
string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
string pattern = @"%(?<Number>\d+(\.\d+)?)?(?<Type>d|f|s)";
int count = 0;
string result = Regex.Replace(input, pattern, m =>
{
var number = m.Groups["Number"].Value;
var type = m.Groups["Type"].Value;
// now you can have custom logic to check the type appropriately
// check the types, format with the count for the current parameter
return String.Concat("{", count++, "}");
});
C # /. NET 2.0 подход:
private int formatCount { get; set; }
void Main()
{
string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
Console.WriteLine(FormatCStyleStrings(input));
}
private string FormatCStyleStrings(string input)
{
formatCount = 0; // reset count
string pattern = @"%(?<Number>\d+(\.\d+)?)?(?<Type>d|f|s)";
string result = Regex.Replace(input, pattern, FormatReplacement);
return result;
}
private string FormatReplacement(Match m)
{
string number = m.Groups["Number"].Value;
string type = m.Groups["Type"].Value;
// custom logic here, format as needed
return String.Concat("{", formatCount++, "}");
}