刚刚试了一下 DelphiXE 新增的正则表达式组件, 它基于 C 语言编写的 PCRE 库实现, 感觉设计的非常好。

其主要的 TRegEx 被设计为一个结构(而不是类), 可能是基于效率的考虑;不过它主要调用了 TPerlRegEx 类的功能。

TRegEx 的五个主要方法 IsMatch()、Match()、Matches()、Replace()、Split() 都有相应的 class 方法,
所以一般情况下根本不需要手动实例化对象,直接使用 class 方法就够了。

另:关于表达式语法可参加 Perl 5 的相关介绍。

uses RegularExpressions; //相关单元

const
  pattern = '[A-Z]+\d+';                      //测试用的表达式
  txt = 'AAA1 BBB2 AA11 BB22 A111 B222 AAAA'; //测试用的目标文本

{是否匹配成功}
procedure TForm1.Button1Click(Sender: TObject);
begin
  if TRegEx.IsMatch(txt, pattern) then
  begin
    ShowMessage('有匹配到');
  end;
end;

{获取第一个匹配结果}
procedure TForm1.Button2Click(Sender: TObject);
var
  match: TMatch;
begin
  match := TRegEx.Match(txt, pattern);
  if match.Success then //或用一句话 if TRegEx.Match(txt, pattern).Success then
  begin
    ShowMessage(match.Value); //AAA1
  end;
end;

{获取所有匹配结果}
procedure TForm1.Button3Click(Sender: TObject);
var
  matchs: TMatchCollection;
  match: TMatch;
  i: Integer;
begin
  matchs := TRegEx.Matches(txt, pattern);

  Memo1.Clear;
  for match in matchs do
  begin
    Memo1.Lines.Add(match.Value);
  end;

  Memo1.Lines.Add('----------');
  for i := 0 to matchs.Count - 1 do
  begin
    Memo1.Lines.Add(matchs[i].Value);
  end;
end;

{使用 TMatch 对象的 NextMatch 遍历匹配结果时,需实例化对象}
procedure TForm1.Button4Click(Sender: TObject);
var
  reg: TRegEx;
  match: TMatch;
begin
  reg := TRegEx.Create(pattern);
  match := reg.Match(txt);

  Memo1.Clear;
  while match.Success do
  begin
    Memo1.Lines.Add(match.Value);
    match := match.NextMatch;
  end;
end;

{替换}
procedure TForm1.Button6Click(Sender: TObject);
begin
  Memo1.Text := TRegEx.Replace(txt, pattern, 'xxx'); //xxx xxx xxx xxx xxx xxx AAAA
end;

{分割}
procedure TForm1.Button7Click(Sender: TObject);
var
  rArr: TArray<string>;
  s: string;
begin
  rArr := TRegEx.Split('AAA,BBB;CCC,DDD EEE', '[,; ]');

  Memo1.Clear;
  for s in rArr do
  begin
    Memo1.Lines.Add(s); //AAA/BBB/CCC/DDD/EEE
  end;
end;

{TRegEx 还有一个 class 方法 Escape, 用于给特殊字符转义}
procedure TForm1.Button8Click(Sender: TObject);
begin
  Memo1.Text := TRegEx.Escape('\[]^$.|?*+(){}'); //: \\\[\]\^\$\.\|\?\*\+\(\)\{\}
end;

posted on 2011-03-28 20:55  万一  阅读(10846)  评论(4编辑  收藏  举报