您的位置:首页 > 编程语言 > Delphi

Delphi 正则表达式 TPerlRegEx 类

2013-10-30 16:52 351 查看
抄自:万一的博客 http://www.cnblogs.com/del/category/113551.html

目录:

基本方法

查找(目标字符串及其属性)

字表达式

限定匹配范围:start、stop

字符串分隔

基本方法

use PerlRegEx; //引用单元

var
reg:TPerlRegEx;  //声明变量类型
begin
reg:= TPerlRegEx.Create; //创建实例
reg.Subject:= 'Goodbye Hello-World !'; //源字符串
reg.RegEx:= '(?<=Goodbye ).*'; //正规表达式
reg.Match; //执行查找
ShowMessage(reg.MatchedText); //输出查找结果
FreeAndNil(reg); //释放内存
end;


查找

//查看是否存在
if reg.Match then ...

or

begin
reg.Match;
if reg.FoundMatch then ...
end


//显示找到的第一个
if reg.Match then
ShowMessage(reg.MatchedText)


//分别显示找到的每一个
while reg.MatchAgain do  //MatchAgain 是下一个
begin
ShowMessage(reg.MatchedText);
Inc(num);
end;


//目标字符串的 位置 和 长度
while reg.MatchAgain do
begin
ShowMessage(reg.MatchedText); //找到的字符串
ShowMessage(IntToStr(reg.MatchedOffset));//位置
ShowMessage(IntToStr(reg.MatchedLength));//长度
end;


子表达式

//字表达式:Groups[Index :Integer]:String;
reg.Subject:= 'Goodbye Hello-World !';
reg.RegEx:= '(?<=Goodbye )(\w*)-?(\w*)';
reg.Match;
for i:= 0 to reg.GroupCount do
begin
ShowMessage(reg.Groups[i]);
end;
//分别显示“Hello-World”,“Hello”,“World”


限定范围:start、stop

//使用不可以使用ReplaceAll ,否则仍会替换全部内容
reg.Subject := 'ababab';
reg.Start := 5;
reg.Stop := 6;
while reg.MatchAgain do
begin
reg.Replace;
end;
ShowMessage(reg.Subject); //返回: abab◆


字符串分隔

reg.Subject := 'aaa,bbb,ccc,ddd';
reg.RegEx   := ','; //确定字符串的分隔符

reg.Split(List,MaxInt); //List: TStrings; 用于存放分割后的字符串
{ 输入一个最大整数, 表示能分多少就分多少}

ShowMessage(List.Text);
{返回:
aaa
bbb
ccc
ddd
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: