Delphi使用正则表达式

Delphi使用正则表达式
2006-09-21 下午 04:24
//轉自:阿勇的BLOG;
//http://www.ainlife.cn
羡慕VB,VBA中那些功能超强又方便的正则表达式吗?如果delphi中也能有那个就好了,可是。。。。好像delphi没有这个功能呢,呵呵,看看我们如何来利用VBScript.dll这个COM组件来完成在Delphi中使用正则表达式的。

1. 下载并安装最新版的"Microsoft(r) Windows(r) Script" 
2. RegExp包含在vbscript.dll中所以我们必须先注册regsvr32 vbscript.dll  
注(安装了Ie5后默认已经包含该控件) 
3.在Delphi中引入"Microsoft VBScript Regular Expressions"  
主菜单->Project->Import type library->在列表中选择"Microsoft VBScript Regular Expressions" 
生成TRegExp控件 
4.使用以下代码调用TRegExp控件 
procedure TForm1.Button1Click(Sender: TObject); 
var 
    machs: IMatchCollection; 
    Matchs: Match; 
    submatch: ISubMatches; 
    i, j: integer; 
begin 
   RegExp1.Global := true; 
   RegExp1.Pattern := ’/w+/./w+(?!.)’; 
   RegExp1.IgnoreCase := true; 
   machs := RegExp1.Execute(’ http://www.ainlife.cn/index.asp’) as IMatchCollection; 
   for i := 0 to machs.Count - 1 do 
   begin 
     Matchs := machs.Item[i] as Match; 
     submatch := Matchs.SubMatches as ISubMatches; 
     memo1.Lines.Add(matchs.Value); 
   end; 
end;

以上是网上流传的资料,我通过这点资料,写了如下代码,需要引用ComObj单元。

procedure TForm1.Button1Click(Sender: TObject);
var
  Matches, MyTest: OleVariant;
  NewTestStr, TestStr: string;
  i: integer;
begin
  TestStr := '网址: http://www.ainlife.cn/  电话:0728-4576983';
  MyTest := CreateOleObject('VBScript.RegExp');
  MyTest.Global := True;
  MyTest.IgnoreCase := True;

  MyTest.Pattern := '[/d]{3,4}-[/d]{6,11}'; //匹配一个电话号码
  if MyTest.Test(TestStr) then ShowMessage('找到了电话号码');

  Matches := MyTest.Execute(TestStr); //执行查找;

  for i := 1 to Matches.count do //显示找到的结果
  begin
    ShowMessage(Format('找到的第%d个:%s', [i, Matches.item[i - 1]]))
  end;

  NewTestStr := MyTest.Replace(TestStr, '0769-85787641');
  ShowMessage(NewTestStr);

end;

其实以上两种办法同出一辙,几乎没有任何区别
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值