RegEx第二次破折号后匹配任何内容

时间:2020-04-21 06:09:38

标签: c# .net regex match regex-group

具有以下字符串样本

"01:23:45 - site name1 - message received1"
"01:23:45 - site name2 - message received2"
"01:23:45 - site name3 - message received3"
"01:23:45 - site name4 - message received4"

我希望得到:

"message received1"
"message received2"
"message received3"
"message received4"

实际上我通过使用this

得到了这个结果
string pattern = @"(?:[^-\n]+-){2}(.*)$";
string input = @"
01:21:42 - site name1 - message received1
02:22:43 - site name2 - message received2
03:23:44 - site name3 - message received3
04:24:45 - site name4 - message received4";

RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;

foreach (Match m in Regex.Matches(input, pattern, options))
{
 Console.WriteLine("{0}", m.Groups[1].Value);
}


但仅作为Group[1]个匹配项,因为在Group[0]中,我得到了每行的完全匹配项。因此,问题是,有什么办法无需与小组打交道就能获得此结果?是否存在与使用多个组有关的性能问题?

2 个答案:

答案 0 :(得分:0)

不使用正则表达式的替代方法

Content-type

输出

application/x-www-form-urlencoded

答案 1 :(得分:0)

.NET支持在后面的{2}中使用量词(?<=

您可以省略RegexOptions.IgnoreCase,因为该模式仅不匹配小写字符。

您可以将模式更改为仅m.Value

 (?<=(?:[^-\n]+-){2}).+$

.NET Regex demo

例如

string pattern = @"(?<=(?:[^-\n]+-){2}).+$";
string input = @"
01:21:42 - site name1 - message received1
02:22:43 - site name2 - message received2
03:23:44 - site name3 - message received3
04:24:45 - site name4 - message received4";

RegexOptions options = RegexOptions.Multiline;

foreach (Match m in Regex.Matches(input, pattern, options))
{
    Console.WriteLine("{0}", m.Value);
}

输出

 message received1
 message received2
 message received3
 message received4