我有一个示例String:
There are from {d} to {d} {s} balls available. Average of {f} balls.
我想查找这些标记的所有内容:{d}
,{f}
和{s}
。
那是什么样的正则表达式?
答案 0 :(得分:3)
我会这样做,
\{[dsf]\}
\{
,\}
与文字{
,}
符号相匹配。
[dsf]
与给定列表中的单个字符匹配的字符类,即d
或s
或f
答案 1 :(得分:1)
答案 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);
}
}
}
}