主要成员有: IRegex、ICapture、IMatch、IMatchCollection、IGroup、IGroupCollection
先看: ICapture; 常用的 IMatch、IGroup 都是从它继承而来; 作为一个底层接口一般不会被直接使用.
它为 IMatch、IGroup 提供了三个属性: Index、Length、Value; 还有一个 ToString 方法也是获取 Value.
IMatchCollection、IGroupCollection 分别是 IMatch、IGroup 的集合.
作为集合都有 Count 属性和 Items[] 属性; 它们的 GetEnumerator 方法支持了 for in 循环.
和线程支持相关的三个属性: IsReadOnly、IsSynchronized、SyncRoot 在当前版本并没有实现.
另外 IGroupCollection 比 IMatchCollection 多出来一个 ItemsByName[] 属性, 用于获取指定名称的子表达式, 如:
uses RegularExpressions; procedure TForm1.FormCreate(Sender: TObject); var Regex: IRegex; Match: IMatch; w,n: string; begin Regex := TRegex.Create('(?<Name1>[A-Za-z]+)(?<Name2>\d+)'); Match := Regex.Match('AAA1 BBB2 AA11 BB22 A111 B222 AAAA'); while Match.Success do begin w := Match.Groups.ItemsByName['Name1'].Value; { AAA ...} n := Match.Groups.ItemsByName['Name2'].Value; {1 ...} ShowMessageFmt('%s, %s', [w, n]); Match := Match.NextMatch; end; end;
IMatchCollection 在当前版本应该尽量少用, 因为有个 bug:
获取 IMatchCollection 后, 其中的 IMatch 对象不包含子表达式的信息!
假如不需要子表达式的信息, 则可以使用(假如需要可以使用 IMatch.NextMatch 方法, 前面有例子):
uses RegularExpressions; procedure TForm1.FormCreate(Sender: TObject); var Regex: IRegex; Input, Pattern: string; MatchCollection: IMatchCollection; Match: IMatch; begin Pattern := '([A-Za-z]+)(\d+)'; Input := 'AAA1 BBB2 AA11 BB22 A111 B222 AAAA'; Regex := TRegex.Create(Pattern); MatchCollection := Regex.Matches(Input); for Match in MatchCollection do begin ShowMessage(Match.Value); end; end;
IMatch 与 IGroup 是两个重要的对象接口.
IMatch 是表达式匹配的结果;
其 Success 方法表示匹配是否成功;
其 NextMatch 方法是继续匹配下一个, 并返回下一个 IMatch 对象.
IGroup 表示一个子表达式的匹配结果, 一个 IMatch 中可能会包含若干个 IGroup.
下面程序可遍历出所有匹配到的子表达式:
uses RegularExpressions; procedure TForm1.FormCreate(Sender: TObject); var Regex: IRegex; Input, Pattern, str: string; Match: IMatch; Group: IGroup; begin Pattern := '([A-Za-z]+)(\d+)'; Input := 'AAA1 BBB2 AA11 BB22 A111 B222 AAAA'; Regex := TRegex.Create(Pattern); Match := Regex.Match(Input); while Match.Success do begin for Group in Match.Groups do begin Memo1.Lines.Add(Group.Value); end; Match := Match.NextMatch; end; end;
说没了, 只剩 IRegex 了.
分类:
Delphi 与正则表达式
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
2009-01-07 Delphi 与 DirectX 之 DelphiX(1): 安装测试
2009-01-07 求助! 谁有 《inside delphiX》这本书?
2009-01-07 模拟点击网页中的按钮 - 回复 "starcraft_ly" 的问题
2008-01-07 Delphi 中的 XMLDocument 类详解(19) - NodeValue 与 NodeName 的读写区别
2008-01-07 Delphi 中的 XMLDocument 类详解(18) - 更好地显示 xml 的测试结果 - FormatXMLData 及其他