它应符合以下标准(条件部分在方括号中:
%[some numbers][.some numbers]d|f|s
符号d | f | s表示其中一个必须在那里.
谢谢& BR -Matti
解决方法
这应该这样做:
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],因为我计划更新它以使用命名组.这是基于your earlier question关于确定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,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++,"}"); }