代码之家  ›  专栏  ›  技术社区  ›  Tom

如何从字符串中提取格式化部分

  •  0
  • Tom  · 技术社区  · 17 年前

    如果我有一个string=“警告:错误{0}已经发生。{1,9}模块已{2:0%}完成。“ 我想将{0}、{1,9}和{2:0%}提取到一个sting数组中。有没有一个正则表达式或者别的什么方法可以实现,而不是我用子串索引'{'和'}'交替循环字符串的方法?

    4 回复  |  直到 17 年前
        1
  •  1
  •   Colin Burnett    17 年前

    “\{[^}]+\}”的一些变体会不会不起作用?通过查找匹配项和从头到尾的子串来运行它。

        2
  •  1
  •   THX-1138    17 年前

    以下代码不同于其他答案,因为它使用非贪婪匹配(“*”?):

        private static void Main(string[] args) {
            const string input = "Warning: the error {0} has occurred. {1, 9} module has {2:0%} done.";
            const string pattern = "{.*?}"; // NOTE: "?" is required here (non-greedy matching).
            var formattingParts = Regex.Matches(input, pattern).Cast<Match>().Where(item => item.Success).Select(item => item.Groups[0].Value);
            foreach (var part in formattingParts) {
                Console.WriteLine(part);
            }
        }
    
        3
  •  0
  •   Jordan S. Jones    17 年前
    new Regex(@"\{[0-9:,% .]+\}");
    

        4
  •  0
  •   Ethan Heilman    17 年前

    在Java中 Matcher 类接受正则表达式并将返回所有匹配的子字符串。

    String str = "Warning: the error {0} has occurred. {1, 9} module has {2:0%} done.";
    
    Matcher matcher = pattern.matcher( "{.*}");
    while (matcher.find()){
        String matched = matcher.group()
        \\do whatever you want with matched
    }