官方的正则表达式组件 RegularExpressions (2) : 子表达式



uses RegularExpressions;



const

  pattern = '([A-Z]+)(\d+)'; //其三个子表达式分别是:[A-Z]+\d+  [A-Z]+  \d+

  txt = 'AAA1 BBB2 AA11 BB22 A111 B222 AAAA'; //测试用的目标文本



procedure TForm1.Button1Click(Sender: TObject);

var

  match: TMatch;

  group: TGroup;

  groups: TGroupCollection;

begin

  match := TRegEx.Match(txt, pattern);

  groups := match.Groups;



  Memo1.Clear;

  for group in groups do

  begin

    Memo1.Lines.Add(group.Value); //AAA1/AAA/1

  end;

end;



procedure TForm1.Button2Click(Sender: TObject);

var

  match: TMatch;

  group: TGroup;

begin

  Memo1.Clear;

  for match in TRegEx.Matches(txt, pattern) do

  begin

    for group in match.Groups do

    begin

      Memo1.Lines.Add(group.Value);

    end;

    Memo1.Lines.Add('');

  end;

end;

{**************

AA11

AA

11



BB22

BB

22



A111

A

111



B222

B

222

**************}



procedure TForm1.Button3Click(Sender: TObject);

var

  rStr: string;

begin

  Memo1.Clear;

  rStr := TRegEx.Replace(txt, pattern, '$1');   //AAA BBB AA BB A B AAAA

  Memo1.Lines.Add(rStr);



  rStr := TRegEx.Replace(txt, pattern, '$2');   //1 2 11 22 111 222 AAAA

  Memo1.Lines.Add(rStr);



  rStr := TRegEx.Replace(txt, pattern, '$2$1'); //1AAA 2BBB 11AA 22BB 111A 222B AAAA

  Memo1.Lines.Add(rStr);

end;

{**********************************

AAA BBB AA BB A B AAAA

1 2 11 22 111 222 AAAA

1AAA 2BBB 11AA 22BB 111A 222B AAAA

***********************************}


你可能感兴趣的:(express)