正则表达式在处理和匹配字符串中用处颇大。在此转载一篇有关正则表达式用法的博文,并通过实际的报表模块说明正则表达式的用法。






在实际的项目中,用到正则表达式的地方也是不少。现在拿Excel模板中的标签解析机制做说明。

private List<string> GetDataSourceLabelByType(Sheet sheet, string sourcetype)
{
List<string> list = new List<string>();
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
while (rows.MoveNext())
{
Row row = (Row)rows.Current;
System.Collections.IEnumerator cells = row.GetCellEnumerator();
while (cells.MoveNext())
{
Cell cell = (Cell)cells.Current;
if (cell == null || cell.CellType != CellType.STRING || cell.StringCellValue == null)
{
continue;
}
string cellvalue = cell.StringCellValue;
//获取所有标签
MatchCollection mc = Regex.Matches(cellvalue, @"<[^>]+\*>");
if (mc.Count > 0)
{
foreach (Match match in mc)
{
string tag = match.Value.ToUpper();
object tagvalue = "";
if (tag.StartsWith(sourcetype))
{
list.Add(cellvalue);
}
}
}
}
}
return list;
}
浙公网安备 33010602011771号