http://www.jbtraining.com.cn/base/net/608.html :原地址
什么是正则表达式?
正则表达式就是一个字符串,正则表达式是用来匹配数据的,和语言无关,在js中也要用到。正则表达式类似于通配符,但又不仅仅是通配符。
注意:不要想着一次性写出通用的正则表达式,够用就行,不行再改。
文字与非文字
文字(数字,字母和汉字,不包含标点符号):
文字:\w
非文字:\W
注意点:字符串转义与c#转义相同。即在文字前面加上一个@,例如:@"@\w",找出以@开头的说有匹配文字。
在.Net中我们使用Regex类来书写正则表达式
Regex的常用方法:
IsMatch():判断是否匹配
Match():字符串提取
Matches():循环提取
Replace():Replace()
例子:用正则表达式把HashTable中的数据一条条的读出来。
string str = @"insert into student values(@sname,@gender,@age)";
Hashtable table = new Hashtable();
table.Add("@sname", "揽月");
table.Add("@gender", "女");
table.Add("@age", "24");
MatchCollection MC = Regex.Matches(sql, @"@\w+");//MatchCollection:所有匹配的内容保存位置;Match是它的数据类型。
foreach (Match mc in MC)
{
string key = mc.Value;
Console.WriteLine(key);
object Value = table[key];
Console.WriteLine(Value);
}
这个例子在miniUI中传递sql时会用到。因为在MiniUI中页面表单中的数据是通过form传递,而在得到数据的时候用的是json.net,所以会用到ArrayList和HashTable,即本例中的这部分代码。
下面的“添加”是在表单通过Form提交后,并通过json.net把数据保存到HashTable后的那部分代码:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;//正则表达式的命名空间
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
/// <summary>
/// 添加数据
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
#region
string ConnStr = "data source=.;initial catalog=Student;user id=sa; pwd=sa";
SqlConnection sqlConn = new SqlConnection(ConnStr);
SqlCommand sqlCmd = sqlConn.CreateCommand();
string sql = "insert into student values(@sname,@gender,@age)";
//看如何把HashTable中的数据保存到sql语句中
Hashtable table = new Hashtable();
table.Add("@sname", "揽月");
table.Add("@gender","女");
table.Add("@age", "66");
MatchCollection ic = Regex.Matches(sql,@"@\w+");
foreach (Match lst in ic)
{
string key = lst.Value;
object value = table[key];
Console.WriteLine(value);
if (value == null)
{
value = table[key.Substring(1)];
}
if (value == null)
{
value = DBNull.Value;
}
sqlCmd.Parameters.Add(new SqlParameter(key,value));
sqlCmd.CommandText = sql;
}
try
{
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
#endregion
}
}
}
}
注意:
@\w+:即找出以@开头的文字,如查出@sname;
@\w:即找出以@开头的文字,如查出@sname中的@s。