正则表达式
来源:互联网 发布:小语网络加速器下载 编辑:程序博客网 时间:2024/06/06 05:28
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。
- 【正则表达式】正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- 正则表达式
- iphone空间尺寸集合
- Visual C++线程同步技术剖析:临界区,时间,信号量,互斥量
- yii Controller 访问控制过滤器 使用 摘记
- 亮剑.NET的系列文章之ADO.NET五大类(二)
- ASI 详解
- 正则表达式
- MUTC 1 B - Hourai Jeweled 树形dp?
- android taskAffinity allowTaskReparenting
- selenium webdriver学习(十六)----------用selenium webdriver实现selenium RC中的类似的方法
- Windows 8 下配置Cocos2d-x + Android + Eclipse 的开发环境
- eclipse打签名包无法生成apk由于Lint Error导致失败解决办法
- FAST_START_MTTR_TARGET参数
- 关于段错误的看法。。。
- struts2的细粒度的权限拦截