正则表达式到行尾

问题描述 投票:3回答:2

我想使用正则表达式在字符串中查找注释行。我尝试了以下但它在第一次//之后给了我一切。

为什么?

program Project1;

uses
  RegularExpressions;

var
  Text: string;
  Pattern: string;
  RegEx: TRegEx;
  Match: TMatch;
begin
  Text := 'Hello' + #13#10
    + '// Test' + #13#10
    + 'Text' + #13#10;

  Pattern := '//[^$]*$';

  RegEx := TRegEx.Create(Pattern, [roCompiled, roMultiLine]);
  Match := RegEx.Match(Text);
  if (Match.Success) then
  begin
    Match.Index; // 8 -> Expected
    Match.Length; // 15 -> I would like to have 9
  end;
end.
regex delphi
2个回答
1
投票

你需要使用

Pattern := '//.*';

您甚至可以删除roMultiLine选项,因为您不需要指定行尾,.*将匹配除换行符之外的0+字符,实际上将任何行匹配到当前位置(此处,在//之后)。


1
投票

您不应在正则表达式中使用以下语法:[^$]*

这意味着所有不是美元$ 0到N次(包括EOL字符)的字符会导致你的正则表达式占用整个字符串。

使用该正则表达式:

 Pattern := '//[^\r\n]*'

祝好运!

© www.soinside.com 2019 - 2024. All rights reserved.