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

前端之家收集整理的这篇文章主要介绍了官方的正则表达式组件 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,'$2');   //1 2 11 22 111 222 AAAA
  Memo1.Lines.Add(rStr);

  rStr := TRegEx.Replace(txt,'$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
***********************************}
原文链接:https://www.f2er.com/regex/361261.html

猜你在找的正则表达式相关文章