gpt4 book ai didi

regex - 正则表达式到行尾

转载 作者:行者123 更新时间:2023-12-03 15:55:48 26 4
gpt4 key购买 nike

我想使用正则表达式查找字符串中的注释行。我尝试了以下操作,但它给了我第一个 // 之后的所有内容。

为什么?

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.

最佳答案

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

这意味着将所有非美元字符 $ 取 0 到 N 次(包括 EOL 字符),这会导致您的正则表达式取整个字符串。

改用该正则表达式:

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

祝你好运!

关于regex - 正则表达式到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47864250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com