匹配模式到行尾

Matching pattern to end of line

我正在尝试从文本文件中获取一些内联注释,需要一些有关表达式的帮助。

this comes before selection
this is on the same line %% this is the first group and it can have any character /[{3!+-p
here is some more text in the middle
this stuff is also on a line with a comment %% this is the second group of stuff !@#%^()<>/~`
this goes after the selections

我正在尝试获取 %%\s+ 之后的所有内容。这是我尝试过的:

%%\s+(.*)$

但是匹配第一个 %% 之后的所有文本。不知道从这里去哪里。

由于 . 默认匹配除换行符以外的任何字符,因此您无需使用 $:

%%\s+(.*)

regex demo

解释:

  • %% - 两个文字 % 符号
  • \s+ - 1 个或更多空格
  • (.*) - 0 个或多个除换行符以外的任何字符(捕获到第 1 组)

C# demo:

var s = "THE_STRING";
var result = Regex.Matches(s, @"%%\s+(.*)")
            .Cast<Match>()
            .Select(p=>p.Groups[1].Value)
            .ToList();
Console.WriteLine(string.Join("\n", result));

大多数引擎默认点不匹配换行符
AND 不是多行模式。

这意味着 %%\s+(.*)$ 不应该匹配,除非它找到
%% 在字符串的最后一行。

与其尝试对抗它,不如使用内联修饰符 (?..) that
覆盖 外部开关。

使用 (?-s)%%\s+(.*) 关闭 点全部