关于模版匹配

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
//手动判别字符串匹配{#(1-6)}
//# :汉字或者·
//1-6 :表示最少一个最多6个
//* :表示字母数字或者特殊字符
//缺陷:1.#只能出现一次
// 2.两个*不能相连,比如:{*(1-6)}{*(1-6)}这样验证会有BUG
// 3.#必须在*之前,比如:{*(1-6)}XX{#(1-6)}这样无法验证
private static bool containt(string str, string temp)
{
bool flag = false;
string[] Str1 = temp.Split('{');
if (str.StartsWith(Str1[0]))
{
str = str.Substring(Str1[0].Length);

for (int k = 0, m = Str1.Length - 1; k < Str1.Length - 1; k++, m--)
{
string[] Str2 = Str1[m].Split('}');
for (int i = 0, j = Str2.Length - 1; i < Str2.Length; i++, j--)
{
if (str.EndsWith(Str2[j]))
{
int len = str.Length;
str = str.Substring(0, len - Str2[j].Length);
}
else if (Str2[j].StartsWith("#") || Str2[j].StartsWith("*"))
{
int min = int.Parse(Str2[j].Split(',')[0].Substring(2));
int max = int.Parse(Str2[j].Split(',')[1].Substring(0, Str2[j].Split(',')[1].Length - 1));
if (Str2[j].StartsWith("#"))
{
if (str.Length >= min && str.Length <= max && new Regex(@"^[\u4e00-\u9fa5\uf900-\ufa2d·s]+$").IsMatch(str))
{
flag = true;
}
}
else if (Str2[j].StartsWith("*"))
{
for (int n = max; n >= min; n--)
{
string last = str;
if (last.Length>=n)
{
if (new Regex(@"^[a-zA-Z0-9\\W_]+$").IsMatch(last.Substring(last.Length - n)))
{
str = str.Substring(0, str.Length - n);
break;
}
}
}
}
else
{
flag = false;
}
}
}
}
}
else
{
flag = false;
}
if (str.Length == 0)
{
flag = true;
}
return flag;
}
//完全通过正则表达式验证#{1,6}或者*{1,6},替换成正则后直接验证,效率高正确率高
private static bool containtreg(string str, string temp)
{
bool flag = false;
temp = temp.Replace("#", "[\u4e00-\u9fa5\uf900-\ufa2d·s]");
temp = temp.Replace("*", "[a-zA-Z0-9\\W_]");
flag = new Regex(@"^" + temp + "$").IsMatch(str);
return flag;
}
static void Main(string[] args)
{
string a = "尊敬的杨先生,你的手机1@0.8_拨打不同";
string b = "尊敬的{#(1,6)}先生,你的手机{*(1,6)}拨打不同";
string c = "尊敬的#{1,6}先生,你的手机*{1,6}拨打不同";
string d = "尊敬的[\u4e00-\u9fa5\uf900-\ufa2d·s]{1,6}先生,你的手机[a-zA-Z0-9\\W_]{1,6}拨打不同";
bool f=containt(a, b);//返回true
bool f1 = containtreg(a,c);//返回true
//直接验证表达式,实际运用当中不多
bool f2= new Regex("^"+d+"$").IsMatch(a);//返回true
return;
}
}
}

转载于:https://www.cnblogs.com/yangfan5157/p/10576907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值