用正则表达式获取指定的字符串

有一网友问了一个有关正则的问题,即取出以单词begin开头和单词end结尾之间的字符串,很感兴趣便动手试下,可试了很多次效果不是太理想,今天简单的实现了,代码如下:

unit Unit1;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, RegularExpressions, StdCtrls;



type

  TForm1 = class(TForm)

    Button1: TButton;

    Edit1: TEdit;

    Memo1: TMemo;

    Label1: TLabel;

    Label2: TLabel;

    procedure Button1Click(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;



var

  Form1: TForm1;



implementation



{$R *.dfm}



procedure TForm1.Button1Click(Sender: TObject);

var

  Regex: TRegex;

begin

  Regex := TRegex.Create(Edit1.Text, [roIgnoreCase]);

  try

    if Regex.Match(Memo1.Text).Success then

      begin

        ShowMessage(Regex.Match(Memo1.Text).Value);

      end;

  finally



  end;

end;



end.

  (注:开发环境XE)

Edit1.Text := '(?<=Begin)([.\S\s]*)(?=End)';//正则


Memo1.Text:= 'dklewjsabegindiekdjekdenickdkekkdiuiuijujenddkeidkkd'

内容中可以有换行符,这里只是简单的实现,可能还有些情况要处理,比如内容中不只一个begin~end,这就要另作处理了

你可能感兴趣的:(正则表达式)