参考: http://www.cnblogs.com/deerchao/archive/2006/08/24/zhengzhe30fengzhongjiaocheng.html
1,判断字符串中是否含有中文
using System.Text.RegularExpressions;
if (Regex.IsMatch(gst.Customer.EnglishName, @"[\u4e00-\u9fa5]+"))
{
ShowMessage("客人的英文名含有汉字");
return;
}
2,截取中间部分字符串
//string s = Regex.Replace(" abra ", @"^\s*(.*?)\s*$", "$1");
//return s; // 返回abra(它前后的空格被去掉了)
Regex.Replace("abcdef009gasdf879653", "^.*09(.*?)879.*$", "$1") 将会返回gasdf
Regex.Replace(ctx, ".*<div class=\"sl_top\"> <b><a name=\"top\"></a>首尾班车时刻表</b>(.*?)</div> <p class=\"notice\">注:.*", "$1")
3,截取字符串中的数字
string sTest = "3239*aa";
string sResult = Regex.Replace(sTest, @"[^\d]", ""); // 返回3239
4, 分组匹配
\b\w+(?=ing\b)
I'm singing while you're dancing.
能匹配到2个结果: sing 和 danc
\b\w*q[^u]\w*\b
Iraq fighting how
匹配到1个结果:Iraq fighting
原始字符串->constraint "FK_q_contract_q_1quote". database "QBaseDemoS1", table "dbo.q_contract", column 'quote_id'.
正则表达式->^.*constraint "(.*?)". database "(.*?)", table "(.*?)", column '(.*?)'..*$
原始字符串->The DELETE statement conflicted with the REFERENCE constraint "FK_q_contract_q_1quote". The conflict occurred in database "QBaseDemoS1", table "dbo.q_contract", column 'quote_id'.
正则表达式->^.*REFERENCE constraint "(.*?)".*database "(.*?)", table "(.*?)", column '(.*?)'..*$
{
Regex r = new Regex(@"^.*REFERENCE constraint ""(.*?)"".*database ""(.*?)"", table ""(.*?)"", column '(.*?)'..*$", RegexOptions.Compiled);
return r.Match(sContent).Result("${1}|${2}|${3}|${4}"); //返回FK_q_contract_q_1quote|QBaseDemoS1|dbo.q_contract|quote_id
}
// 测试内容http://www.yahoo.com.cn:8080/index.html
private String Extension1(String sContent)
{
Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>\d+)?/", RegexOptions.Compiled);
return r.Match(sContent).Result("${proto}|${port}"); //返回http|8080
}
5, 4个样例
LIFEPRINT20130928.ZIP
LIFEPRINT_ASM_ENCOUNTERS20130928_2013-10-25_0534.txt
WMCOSMOS20140115_RXCHF70CL.TXT
分别对应 正则表达式:
^\w+\d{8}\.zip$
^.*_\d{4}-\d{2}-\d{2}_\d{4}\.txt$
^WMCOSMOS\d{8}_RXCHF70CL.TXT$
Regex.IsMatch("FileB_837I_PHC_5010_1191058614_PHC_TX_837I_03272014.xml", "^FileB_837(.*?)xml$",RegexOptions.IgnoreCase)
用Directory.GetFile 则 需这样:string[] arrDoneFile = System.IO.Directory.GetFiles(sNewDone,"FileB_*.xml");
6, 检查字符串A中是否包含字符串B
A= sPageInfo
B= "<div id=\"dvError\" style=\"color:blue;font-size:30px;\"><br />系统忙,请稍侯重试!</div>" --> B
Regex.Matches(A,B).Count >=1 表示 A包含B
eg: Regex.Matches(sPageInfo, "<div id=\"dvError\" style=\"color:blue;font-size:30px;\"><br />系统忙,请稍侯重试!</div>").Count
7,正则移除部分字符串
String sTest = "你好吗,我是小王!(备注1:我们是同事)(备注2:我们还是邻居)【备注3:我们都是开发人员】[备注4:都搞.net]都擅长Oracle操作";
sTest = Regex.Replace(sTest, @"\(.*\)", "");//结果:你好吗,我是小王!(备注2:我们还是邻居)【备注3:我们都是开发人员】[备注4:都搞.net]都擅长Oracle操作
sTest = Regex.Replace(sTest, @"(.*)", "");//结果:你好吗,我是小王!【备注3:我们都是开发人员】[备注4:都搞.net]都擅长Oracle操作
sTest = Regex.Replace(sTest, @"【.*】", "");//结果:你好吗,我是小王![备注4:都搞.net]都擅长Oracle操作
sTest = Regex.Replace(sTest, @"\[.*\]", "");//结果:你好吗,我是小王!都擅长Oracle操作
sTest = Regex.Replace(sTest, @"都擅长.*", "");//结果:你好吗,我是小王!
结束