考虑一个模式:
7 "故障" 6 "保留" 2 "运行" 1 "曲柄" 0 "停止">
我想编写一个正则表达式,用于使用数字作为键和旁边的字符串作为值来构建键值对。
所以对于上面的例子,我希望我的输出为:
键值
- 7 故障
- 6 保留
- 2 跑步
- 1 曲柄
- 0 停止
尝试以下操作:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "7 "Fault" 6 "Reserved" 2 "Running" 1 "Cranking" 0 "Stop"";
string pattern = "(?'key'\d+)\s+"(?'value'[^"]+)"";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches.Cast<Match>())
{
Console.WriteLine("{0} {1}", match.Groups["key"].Value, match.Groups["value"].Value);
}
Console.ReadLine();
}
}
}