c#regex:从括号中获取数字

时间:2013-08-06 06:57:38

标签: c# regex winforms

我写了正则表达式来分离一些文本。我也想从这个括号'[]'中获得价值。这就是我到目前为止所做的:

Regex(@"^(?:(?<C0>Message) from (?<C1>\S+) (?<C2>\S+) to (?<C3>\S+) (?<C4>\S+) (?<C5>.+))$");

这是我的文字示例:

Message from device type[3] to receiver type[45] done;

我希望能够将单词类型和数字3和45分开。现在我只得到类型[3]和类型[45]。

3 个答案:

答案 0 :(得分:2)

 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获取n2type[...]

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仅在type中获取ntype[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

答案 1 :(得分:1)

如果修复此格式,只需在正确的位置添加更多命名组

Regex(@"^(?:(?<C0>Message) from (?<C1>\S+) (?<C2>\S+)\[(?<C2n>\d+)\] to (?<C3>\S+) (?<C4>\S+)\[(?<C4n>\d+)\] (?<C5>.+))$");

然后你可以得到数字

match.Groups["C2n"].Value

答案 2 :(得分:0)

我不知道你需要的是什么:让我知道

 MatchCollection names = Regex.Matches("Message from device type[3] to receiver type[45] done;", @"Message from device type\[(3)\] to receiver type\[(45)\] done;");

  names[0].Groups[1].Value
  names[0].Groups[2].Value