Regex reg = new Regex(@"^(?:(?<C0>Message) from (?<C1>\S+) (?<C2>\S+\[(?<N1>\d+)\]) to (?<C3>\S+) (?<C4>\S+\[(?<N2>\d+)\]) (?<C5>.+))$");
Match m = reg.Match("Message from device type[3] to receiver type[45] done");
var n1 = m.Groups["N1"].Value;//3
var n2 = m.Groups["N2"].Value;//45
您还可以从n1
:n2
type[...]
Regex reg2 = new Regex(@"\S+\[(\d+)\]");
var n1 = reg2.Match(m.Groups["C2"].Value).Groups[0].Value;
var n2 = reg2.Match(m.Groups["C4"].Value).Groups[0].Value;
//or don't use Regex once you get `type[...]`
var s = m.Groups["C2"].Value.Split(new string[]{"[","]"}, StringSplitOptions.RemoveEmptyEntries);
var t = s[0];//type
var n = s[1];//3
如果使用Regex
to get onlytype
和n
in type[n]
:
Regex reg = new Regex(@"^(?:(?<C0>Message) from (?<C1>\S+) (?<T1>\S+)\[(?<N1>\d+)\] to (?<C3>\S+) (?<T2>\S+)\[(?<N2>\d+)\] (?<C5>.+))$");
var t1 = m.Groups["T1"].Value;//type
var n1 = m.Groups["N1"].Value;//3
var t2 = m.Groups["T2"].Value;//type
var n2 = m.Groups["N2"].Value;//45