• Delphi 正则表达式 TPerlRegEx 类


    抄自:万一的博客 http://www.cnblogs.com/del/category/113551.html

    目录:

    1. 基本方法
    2. 查找(目标字符串及其属性)
    3. 字表达式
    4. 限定匹配范围:start、stop
    5. 字符串分隔

     

    基本方法

    use PerlRegEx; //引用单元
    
    var
      reg:TPerlRegEx;  //声明变量类型
    begin
      reg:= TPerlRegEx.Create; //创建实例
      reg.Subject:= 'Goodbye Hello-World !'; //源字符串
      reg.RegEx:= '(?<=Goodbye ).*'; //正规表达式
      reg.Match; //执行查找
      ShowMessage(reg.MatchedText); //输出查找结果
      FreeAndNil(reg); //释放内存
    end;

    查找

    //查看是否存在
    if reg.Match then ...
    
    or
    
    begin
        reg.Match;
        if reg.FoundMatch then ...
    end
    //显示找到的第一个
      if reg.Match then
        ShowMessage(reg.MatchedText)  
    //分别显示找到的每一个
      while reg.MatchAgain do  //MatchAgain 是下一个
      begin
        ShowMessage(reg.MatchedText);
        Inc(num);
      end;
    //目标字符串的 位置 和 长度
      while reg.MatchAgain do 
      begin
        ShowMessage(reg.MatchedText); //找到的字符串
        ShowMessage(IntToStr(reg.MatchedOffset));//位置
        ShowMessage(IntToStr(reg.MatchedLength));//长度 
      end;

    子表达式

    //字表达式:Groups[Index :Integer]:String;
      reg.Subject:= 'Goodbye Hello-World !';
      reg.RegEx:= '(?<=Goodbye )(w*)-?(w*)';
      reg.Match;
      for i:= 0 to reg.GroupCount do
      begin
        ShowMessage(reg.Groups[i]);
      end;
    //分别显示“Hello-World”,“Hello”,“World”

     限定范围:start、stop

    //使用不可以使用ReplaceAll ,否则仍会替换全部内容
      reg.Subject := 'ababab';
      reg.Start := 5;
      reg.Stop := 6;
      while reg.MatchAgain do
      begin
        reg.Replace;
      end;
      ShowMessage(reg.Subject); //返回: abab◆

    字符串分隔

      reg.Subject := 'aaa,bbb,ccc,ddd';
      reg.RegEx   := ','; //确定字符串的分隔符
    
      reg.Split(List,MaxInt); //List: TStrings; 用于存放分割后的字符串
      { 输入一个最大整数, 表示能分多少就分多少}
    
      ShowMessage(List.Text);
      {返回:
        aaa
        bbb
        ccc
        ddd
      }
  • 相关阅读:
    [备份]部分常用函数
    [考试]20150904
    [考试]20150903
    [未完成][知识点]动态规划优化初步
    [考试]20150822
    [考试]20150821
    [知识点]后缀数组
    [考试]20150816
    [考试]20150815
    BZOJ2815: [ZJOI2012]灾难
  • 原文地址:https://www.cnblogs.com/laymond/p/3397222.html
Copyright © 2020-2023  润新知