如何查找多个字符串的所有出现?

时间:2015-06-07 09:31:57

标签: regex

我有一个示例String:

There are from {d} to {d} {s} balls available. Average of {f} balls.

我想查找这些标记的所有内容:{d}{f}{s}

那是什么样的正则表达式?

3 个答案:

答案 0 :(得分:3)

我会这样做,

\{[dsf]\}
  • \{\}与文字{}符号相匹配。

  • [dsf]与给定列表中的单个字符匹配的字符类,即dsf

答案 1 :(得分:1)

将以下正则表达式与全局修饰符一起使用:

/\{[dfs]\}/g

请参阅演示https://regex101.com/r/hZ6gO4/1

[dfs]是一个字符类,它将匹配其中的一个字符!

答案 2 :(得分:-1)

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "There are from 5 to 7 red balls available. Average of 10.3 balls.\n" +
                "There are from 3 to 6 blue balls available. Average of 3.5 balls.\n" +
                "There are from 4 to 7 green balls available. Average of 5.6 balls.\n" +
                "There are from 6 to 8 yellow balls available. Average of 16.7 balls.\n" +
                "There are from 4 to 9 purple balls available. Average of 10.4 balls.\n" +
                "There are from 6 to 8 orange balls available. Average of 17.6 balls.\n" +
                "There are from 7 to 7 white balls available. Average of 18.6 balls.\n" +
                "There are from 4 to 6 black balls available. Average of 3.7 balls.\n" +
                "There are from 5 to 9 tan balls available. Average of 5.6 balls.\n";

            string pattern = @"(?'min'\d+) to (?'max'\d+) (?'color'\w+)[^\d]+(?'average'\d+\.\d+)";

            Regex expr = new Regex(pattern);
            MatchCollection matches = expr.Matches(input);

            List<string> results = new List<string>();
            foreach (Match match in matches)
            {
                string CSV = string.Join(",", new string[] {
                    match.Groups["min"].Value, match.Groups["max"].Value, match.Groups["color"].Value, match.Groups["average"].Value
                });
                results.Add(CSV);
            }
        }
    }
}
​