user7421317
user7421317

Reputation:

Regular Expression to end of line

I'd like to find commented lines within a string using regular expressions. I tried the following but it gives me everything after the first //.

Why?

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.

Upvotes: 4

Views: 24811

Answers (2)

Allan
Allan

Reputation: 12438

You should not use the following syntax in your regex: [^$]*

This means taking all characters that are not dollar $ 0 to N times (including EOL character) what causes your regex to take the whole string.

Use that regex instead:

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

Good luck!

Upvotes: 5

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You need to use

Pattern := '//.*';

You may even remove the roMultiLine option as you do not need to specify the end of line, .* will match 0+ chars other than line breaks, practically matcing any line to its end from the current position (here, after //).

Upvotes: 2

Related Questions