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.
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!
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 //).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With