正则表达式
\w 与任何单词或数字匹配,不匹配特殊符号
\W与\w相反,与任何非单词字符匹配
\s与任何空白字符匹配
\S与\s相反,与任何非空白字符匹配
\d与任何十进制数字匹配。
\D与任何非十进制数字匹配。
[字符分组],与其中的任何字符匹配
[^字符分组],与不在其中的任何字符匹配
* 匹配上一个元素零次或多次
+匹配上一个元素一次或多次
? 匹配上一个元素零次或一次。
概念
则表达式是由普通字符和特殊字符组成的文本模式。该模式用来搜索、替换文本等。例如: 在电脑上我们可以输入*.dat来搜索所有以.dat结尾的文件,输入??.dat来搜索以.dat结尾的有两个字符的文件。
作用
正则表示式可以用来校验数据格式是否符合某个模式(数据校验),例如是否符合电话号码格式或者信用卡模式。
可以用来识别文本中符合模式的字符串,并删除或者替换
可以在模式匹配的基础上,提取字符串。
在.net framework中,正则表示式类是基类库的一部分,开发人员可以快速分析查找大量文本,提取、编辑、替换和删除文本字符串,并将提取的字符串添加到集合以生成报告。
命名空间 using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace RegexTry
{
public partial class FrmRegex : Form
{
public FrmRegex()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//单个查找匹配 match
Regex rgx = new Regex(@"abc\s");
string str = "xxxabc abd ee";
Match m = rgx.Match(str);
if (m.Success)
{
MessageBox.Show("查找到:" + m.Value + " 位置:" +m.Index );
}
//多个查找匹配 MatchCollection
str = "xxxabc sass abc abc ";
string result="" ;
MatchCollection mc = rgx.Matches(str);
for (int i = 0; i <mc.Count; i++)
{
result =result + "查找到:" + mc[i].Value + " 位置:" + mc[i].Index + "\n";
}
MessageBox.Show(result);
}
private void button2_Click(object sender, EventArgs e)
{
//单个查找匹配并分组 group
string str = "xxxabc sass abc abc ";
string result = "";
Regex rgx = new Regex(@"(a)b(c )");
Match m = rgx.Match(str);
for (int i = 0; i < m.Groups.Count; i++)
{
result = result + "提取分组:" + m.Groups[i].Value + " 位置:" + m.Groups[i].Index + "\n";
}
MessageBox.Show(result);
//组的集合
result = "";
GroupCollection gc = rgx.Match(str).Groups;
foreach (Group g in gc)
{
result = result + "提取分组:" + g.Value + " 位置:" + g.Index + "\n";
}
MessageBox.Show(result);
}
private void button3_Click(object sender, EventArgs e)
{
//单个查找匹配并分组 group,捕获子字符串并分组
string str = "xxxabc sass abc abc ";
string result = "";
Regex rgx = new Regex("(?<name1>a)b(?<name2>c\\s)");
Match m = rgx.Match(str);
for (int i = 0; i < m.Groups.Count; i++)
{
result = result + "提取分组:" + m.Groups[i].Value + " 位置:" + m.Groups[i].Index + "\n";
}
MessageBox.Show(result);
MessageBox.Show("组name1:" + m.Groups["name1"].Value + "组name2" + m.Groups["name2"].Value);
}
private void button4_Click(object sender, EventArgs e)
{
//单个查找匹配并分组 group
string str = "sass abc abc xxxabc ";
string result = "";
Regex rgx = new Regex(@"(abc )+");
Match m = rgx.Match(str);
CaptureCollection cc;
for (int i = 0; i < m.Groups.Count; i++)
{
cc= m.Groups[i].Captures;
for (int j = 0; j < cc.Count; j++)
{
result = result + "提取分组:" + cc[j].Value + " 位置:" + cc[j].Index + "长度" + cc[j].Length + "\n";
}
}
MessageBox.Show(result);
}
}
}
项目应用:可以对某一目录下的所有文件是否含有某个控件,进行查询或替换。
查找显示 用listview显示该目录下含有某个字符的文件和以及有几处含有该字符,在进行统一替换。提高开发效率。

浙公网安备 33010602011771号