加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 如何编写C#正则表达式模式以匹配基本的printf格式

发布时间:2020-12-14 05:36:26 所属栏目:百科 来源:网络整理
导读:它应符合以下标准(条件部分在方括号中: %[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 =
它应符合以下标准(条件部分在方括号中:

%[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++,"}");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读