正则表达式辅助类

来源:互联网 发布:初级java工程师考证 编辑:程序博客网 时间:2024/04/29 12:02
using System;
using System.IO;
using System.Text ;
using System.Collections;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

namespace LF.Framework
{
///
/// ------------------------------------------------
/// 创建时间:2005-11-07
/// 正则表达式辅助类
/// 已经通过单元测试
///
public class RegAssist
{
  ///
  /// 查找文本(/w+)英文字母下划线
  ///
  ///
  ///
  ///
  static private MatchCollection findText(string input,string pattern)
  {
  Regex reg = new Regex(pattern);
  return reg.Matches(input);
  }
  ///
  /// 查找在标记中的文本(/w+)英文字母下划线
  ///
  /// 输入字符串
  /// 左标记
  /// 右标记
  /// 查找到的文本集合
  static public StringCollection FindTextBetweenTag(string input,string leftTag,string rightTag)
  {
  leftTag = Regex.Escape(leftTag);
  rightTag = Regex.Escape(rightTag);
  string pattern = @"(?<={0})/w+(?={1})";
  pattern = string.Format(pattern,leftTag,rightTag);

  MatchCollection mc = RegAssist.findText(input,pattern);
  StringCollection sc = new StringCollection();
  foreach(Match m in mc)
  {
    sc.Add(m.Value);
  }
  return sc;
  }
  ///
  /// 替换标记中的文本(/w+)英文字母下划线
  ///
  /// 输入字符串
  /// 左标记
  /// 右标记
  /// 替换文本,如果需要包括原匹配字符串,请使用{0}
  /// 替换后的字符串
  static public string ReplaceBetweenTag(string input,string leftTag,string rightTag,string replacement)
  {
  leftTag = Regex.Escape(leftTag);
  rightTag = Regex.Escape(rightTag);
  string pattern = @"(?<={0})/w+(?={1})";
  pattern = string.Format(pattern,leftTag,rightTag);

  if(replacement.IndexOf("{0}")>=0)
  {
    MatchCollection mc = RegAssist.findText(input,pattern);
    foreach(Match m in mc)
    {
    string ptn = pattern.Replace(@"/w+",m.Value);
    string rep = string.Format(replacement,m.Value);
    Regex reg = new Regex(ptn);
    input = reg.Replace(input,rep);
    }
  }
  else
  {
    input = Regex.Replace(input,pattern,replacement);
  }
  return input;
  }
}
}
原创粉丝点击