WPF基础(十八)C#正则表达式:匹配汉字、特殊字符、字母、数字、IP/端口号等等

目录

第一章、简介

1.1、问题描述

1.2、System.Text.RegularExpressions.Regex.Match介绍

1.2.1、基本规则说明

1.2.2、Regex类常用的方法

1.2.3、Regex类应用举例

1.2.4、正则表达式

第二章、解决方案(WPF Demo)

2.1、WPF Demo

2.2、判断特殊字符(解决AETitle问题)

2.3、判断IP(解决IP地址问题)

2.4、判断端口号(解决端口号问题)

2.5、判断true或false

第三章、实践过程需注意的事项

3.1、验证汉字或中文的正则表达式


第一章、简介

1.1、问题描述

  • 红色矩形的非法输入时,红色椭圆矩形内,会有红色的“*”提示。
  • IP的地址,一定是192.168.1.0这种类型。
  • 端口号一般在1024~65535范围。
  • 需要用到.net正则表达式大全中的Regex.Match,来判断合法输入与否。详情见1.2小结。
  • 表达式不唯一,比如判断IP输入是否正确的方式,就有很多种。

1.2、System.Text.RegularExpressions.Regex.Match介绍

参考:https://www.cnblogs.com/linJie1930906722/p/6092238.html(已经非常详细,但要自己验证才知道怎么用)

1.2.1、基本规则说明

       正则表达式的本质是使用一系列特殊字符模式,来表示某一类字符串。正则表达式无疑是处理文本最有力的工具,而.NET的System.dll类库提供的System.Text.RegularExpressions.Regex类实现了验证正则表达式的方法。Regex 类表示不可变(只读)的正则表达式。它还包含各种静态方法,允许在不显式创建其他类的实例的情况下使用其他正则表达式类。

正则表达式的字符代表的说明:

字符

说明

\

转义字符,将一个具有特殊功能的字符转义为一个普通字符,或反过来

^

匹配输入字符串的开始位置

$

匹配输入字符串的结束位置

*

匹配前面的零次或多次的子表达式

+

匹配前面的一次或多次的子表达式

?

匹配前面的零次或一次的子表达式

{n}

n是一个非负整数,匹配前面的n的次子表达式

{n,}

n是一个非负整数,至少匹配前面的n的次子表达式

{n,m}

m和n均为非负整数,其中n<=m,最少匹配n次且最多匹配m次

?

当该字符紧跟在其他限制符(*,+,?,{n},{n,},{n,m})后面时,匹配模式尽可能少的匹配所搜索的字符串

.

匹配除”\n”之外的任何单个字符

(pattern)

匹配pattern并获取这一匹配

(?:pattern)

匹配pattern但不获取匹配结果

(?=pattern)

正向预查,在任何匹配pattern的字符串开始处匹配查找字符串

(?!pattern)

负向预查,在任何不匹配pattern的字符串开始处匹配查找字符串

x|y

匹配x或者y。例如,’z|food’能匹配”z”或”food”。’(z|f)ood’ 则匹配’zood’或’food’

[xyz]

字符集合。匹配所包含的任意一个字符。例如:’[abc]’可以匹配”plain”中的’a’

[^xyz]

负值字符集合。匹配为包含的任意字符。例如:’[^abc]’可以匹配”plain”中的’p’

[a-z]

匹配指定范围内的任意字符。例如:’[a-z]’可以匹配’a’到’z’范围内的任意小写字母字符

[^a-z]

匹配不在指定范围内的任意字符。例如:’[^b-z]’可以匹配不在 b~z内的任意字符

\b

匹配一个单词边界,指单词和空格间的位置

\B

匹配非单词边界

\d

匹配一个数字字符,等价于[0-9]

\D

匹配一个非数字字符,等价于[^0-9]

\f

匹配一个换页符

\n

匹配一个换行符

\r

匹配一个回车符

\s

匹配任何空白符,包括空格、制表符、换页符等

\S

匹配任何非空白字符

\t

匹配一个制表符

\v

匹配一个垂直制表符,等价于\x0b和\cK

\w

匹配包括下划线的任何单词字符。等价于’[A-Za-z0-9_]’

\W

匹配任何非单词字符,等价于’[^A-Za-z0-9_]’

注意:
由于在正则表达式中“ \ ”、“ ? ”、“ * ”、“ ^ ”、“ $ ”、“ + ”、“(”、“)”、“ | ”、“ { ”、“ [ ”等字符已经具有一定特殊意义,如果需要用它们的原始意义,则应该对它进行转义,例如希望在字符串中至少有一个“ \ ”,那么正则表达式应该这么写: "\\+"

1.2.2、Regex类常用的方法

(1)、静态Match方法
使用静态Match方法,可以得到源中第一个匹配模式的连续子串。
静态的Match方法有2个重载,分别是:

Regex.Match(string input, string pattern);  //第一种重载的参数表示:输入、模式
Regex.Match(string input, string pattern, RegexOptions options);  //第二种重载的参数表示:输入、模式、RegexOptions枚举的“按位或”组合。

RegexOptions枚举的有效值是:

1、None:指定不设置选项。表示无设置,此枚举项没有意义
2、IgnoreCase:指定不区分大小写的匹配。
3、Multiline:多行模式。更改 ^ 和 $ 的含义,使它们分别在任意一行的行首和行尾匹配,而不仅仅在整个字符串的开头和结尾匹配。表示多行模式,改变元字符^和$的含义,它们可以匹配行的开头和结尾
4、ExplicitCapture:指定有效的捕获仅为形式为 (?<name>...) 的显式命名或编号的组。这使未命名的圆括号可以充当非捕获组,并且不会使表达式的语法 (?:...)显得笨拙。表示只保存显式命名的组
5、Compiled:指定将正则表达式编译为程序集。这会产生更快的执行速度,但会增加启动时间。在调用 System.Text.RegularExpressions.Regex.CompileToAssembly(System.Text.RegularExpressions.RegexCompilationInfo[],System.Reflection.AssemblyName)方法时,不应将此值分配给 System.Text.RegularExpressions.RegexCompilationInfo.Options属性。  
6、Singleline :指定单行模式。更改点 (.) 的含义,使它与每一个字符匹配(而不是与除 \n 之外的每个字符匹配)。表示单行模式,改变元字符.的意义,它可以匹配换行符
7、IgnorePatternWhitespace: 消除模式中的非转义空白并启用由 # 标记的注释。但是,System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace值不会影响或消除字符类中的空白。表示去掉模式中的非转义空白,并启用由#标记的注释   
8、RightToLeft:指定搜索从右向左而不是从左向右进行。表示从右向左扫描、匹配,这时,静态的Match方法返回从右向左的第一个匹配
9、ECMAScript: 为表达式启用符合 ECMAScript 的行为。该值只能与 System.Text.RegularExpressions.RegexOptions.IgnoreCase、System.Text.RegularExpressions.RegexOptions.Multiline和 System.Text.RegularExpressions.RegexOptions.Compiled 值一起使用。该值与其他任何值一起使用均将导致异常。表示符合ECMAScript,这个值只能和IgnoreCase、Multiline、Complied连用
10、CultureInvariant: 指定忽略语言中的区域性差异  RegularExpressions Namespace。表示不考虑文化背景
      注意:Multiline在没有ECMAScript的情况下,可以和Singleline连用。Singleline和Multiline不互斥,但是和ECMAScript互斥。

(2)、静态的Matches方法
这个方法的重载形式同静态的Match方法,返回一个MatchCollection,表示输入中,匹配模式的匹配的集合。  
(3)、静态的IsMatch方法
此方法返回一个bool,重载形式同静态的Matches,若输入中匹配模式,返回true,否则返回false。
可以理解为:IsMatch方法,返回Matches方法返回的集合是否为空。

1.2.3、Regex类应用举例

(1)、字符串替换:

//例如我想把如下格式记录中的NAME值修改为YONG
            string line = "ADDR=5449919;NAME=LINJIE;PHONE=45859";
            Regex reg = new Regex("NAME=(.+);");
            string modifiedStr = reg.Replace(line, "NAME=YONG;");

(2)、字符串匹配:

 string line = "ADDR=5449919;NAME=LINJIE;PHONE=45859";
            Regex reg = new Regex("NAME=(.+);");
            //例如我想提取line中的NAME值
            Match match = reg.Match(line);
            string value = match.Groups[1].Value;
            Console.WriteLine("value的值为:{0}", value);

(3)、Match方法的实例

//文本中含有"speed=68.9mph",需要提取该速度值,但是速度的单位可能是公制也可能是英制,mph,km/h,m/s都有可能;另外前后可能有空格。
            string line = "lane=5;speed=68.9mph;acceleration=3.6mph/s";
            Regex reg = new Regex(@"speed\s*=\s*([\d\.]+)\s*(mph|km/h|m/s)*");
            Match match = reg.Match(line);
            //那么在返回的结果中match.Groups[1].Value将含有数值,而match.Groups[2].Value将含有单位。
            var value = match.Groups[1].Value;
            var unit = match.Groups[2].Value;
            Console.WriteLine("speed的值为:{0} speed的单位是:{1}", value, unit);

(4)、解码gps的GPRMC字符串

//就可以获得经度、纬度值
Regex reg = new Regex(@"^\$GPRMC,[\d\.]*,[A|V],(-?[0-9]*\.?[0-9]+),([NS]*),(-?[0-9]*\.?[0-9]+),([EW]*),.*");

(5)、提取[]里面的值

            string pattern = @"(?is)(?<=\[)(.*)(?=\])";
            string result = new Regex(pattern).Match("sadff[我要提取你了]sdfdsf").Value;

(6)、提取()里面的值

            string pattern= @"(?is)(?<=\()(.*)(?=\))";
            string result = new Regex(pattern).Match("sad(我提取到了)dsf").Value;

(7)、提取{}里面的值

 string pattern = @"(?is)(?<=\{)(.*)(?=\})";
string result = new Regex(pattern).Match("sadff[{的d你]srd}sf").Value;
system.Text.RegularExpressions命名空间的说明该名称空间包括8个类,1个枚举,1个委托。他们分别是: Capture: 包含一次匹配的结果;
CaptureCollection: Capture的序列;
Group: 一次组记录的结果,由Capture继承而来;
GroupCollection:表示捕获组的集合
Match: 一次表达式的匹配结果,由Group继承而来;
MatchCollection: Match的一个序列;
MatchEvaluator: 执行替换操作时使用的委托;
RegexCompilationInfo:提供编译器用于将正则表达式编译为独立程序集的信息
RegexOptions 提供用于设置正则表达式的枚举值
Regex类中还包含一些静态的方法:
Escape: 对字符串中的regex中的转义符进行转义;
IsMatch: 如果表达式在字符串中匹配,该方法返回一个布尔值;
Match: 返回Match的实例;
Matches: 返回一系列的Match的方法;
Replace: 用替换字符串替换匹配的表达式;
Split: 返回一系列由表达式决定的字符串;
Unescape:不对字符串中的转义字符转义。

1.2.4、正则表达式

(1)、数字正则表达式

//数字
            Regex reg = new Regex(@"^[0-9]*$");
            //n位的数字
            Regex reg = new Regex(@"^\d{n}$");
            //至少n位的数字
            Regex reg = new Regex(@"^\d{n,}$");
            //m-n位的数字
            Regex reg = new Regex(@"^\d{m,n}$");
            //零和非零开头的数字
            Regex reg = new Regex(@"^(0|[1-9][0-9]*)$");
            //非零开头的最多带两位小数的数字
            Regex reg = new Regex(@"^([1-9][0-9]*)+(.[0-9]{1,2})?$");
            //带1-2位小数的正数或负数
            Regex reg = new Regex(@"^(\-)?\d+(\.\d{1,2})?$");
            //正数、负数、和小数
            Regex reg = new Regex(@"^(\-|\+)?\d+(\.\d+)?$");
            //有两位小数的正实数
            Regex reg = new Regex(@"^[0-9]+(.[0-9]{2})?$");
            //有1~3位小数的正实数
            Regex reg = new Regex(@"^[0-9]+(.[0-9]{1,3})?$");
            //非零的正整数
            Regex reg = new Regex(@"^[1-9]\d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^\+?[1-9][0-9]*$");
            //非零的负整数
            Regex reg = new Regex(@"^\-[1-9][]0-9″*$ 或 ^-[1-9]\d*$");
            //非负整数
            Regex reg = new Regex(@"^\d+$ 或 ^[1-9]\d*|0$");
            //非正整数
            Regex reg = new Regex(@"^-[1-9]\d*|0$ 或 ^((-\d+)|(0+))$");
            //非负浮点数
            Regex reg = new Regex(@"^\d+(\.\d+)?$ 或 ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$");
            //非正浮点数
            Regex reg = new Regex(@"^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 或 ^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$");
            //正浮点数
            Regex reg = new Regex(@"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ 或 ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$");
            //负浮点数
            Regex reg = new Regex(@"^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ 或 ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$");
            //浮点数
            Regex reg = new Regex(@"^(-?\d+)(\.\d+)?$ 或 ^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$");

(2)、普通字符正式表达式

//汉字
            Regex reg = new Regex(@"^[\u4e00-\u9fa5]{0,}$");
            //英文和数字
            Regex reg = new Regex(@"^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$");
            //长度为3-20的所有字符
            Regex reg = new Regex(@"^.{3,20}$");
            //由26个英文字母组成的字符串
            Regex reg = new Regex(@"^[A-Za-z]+$");
            //由26个大写英文字母组成的字符串
            Regex reg = new Regex(@"^[A-Z]+$");
            //由26个小写英文字母组成的字符串
            Regex reg = new Regex(@"^[a-z]+$");
            //由数字和26个英文字母组成的字符串
            Regex reg = new Regex(@"^[A-Za-z0-9]+$");
            //由数字、26个英文字母或者下划线组成的字符串
            Regex reg = new Regex(@"^\w+$ 或 ^\w{3,20}$");
            //中文、英文、数字包括下划线
            Regex reg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");
            //中文、英文、数字但不包括下划线等符号
            Regex reg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9]+$ 或 ^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$");
            //可以输入含有^%&’,;=?$\”等字符
            Regex reg = new Regex(@"[^%&’,;=?$\x22]+");
            //禁止输入含有~的字符
            Regex reg = new Regex(@"[^~\x22]+");

(3)、特殊字符正则表达式

//Email地址
            Regex reg = new Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
            //域名
            Regex reg = new Regex(@"[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?");
            //InternetURL
            Regex reg = new Regex(@"[a-zA-z]+://[^\s]* 或 ^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$");
            //手机号码
            Regex reg = new Regex(@"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$");
            //电话号码(“XXX-XXXXXXX”、”XXXX-XXXXXXXX”、”XXX-XXXXXXX”、”XXX-XXXXXXXX”、”XXXXXXX”和”XXXXXXXX)
            Regex reg = new Regex(@"^($$\d{3,4}-)|\d{3.4}-)?\d{7,8}$");
            //国内电话号码(0511-4405222、021-87888822)
            Regex reg = new Regex(@"\d{3}-\d{8}|\d{4}-\d{7}");
            //身份证号(15位、18位数字)
            Regex reg = new Regex(@"^\d{15}|\d{18}$");
            //短身份证号码(数字、字母x结尾)
            Regex reg = new Regex(@"^([0-9]){7,18}(x|X)?$ 或 ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$");
            //帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线)
            Regex reg = new Regex(@"^[a-zA-Z][a-zA-Z0-9_]{4,15}$");
            //密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线)
            Regex reg = new Regex(@"^[a-zA-Z]\w{5,17}$");
            //强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间)
            Regex reg = new Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$");
            //日期格式
            Regex reg = new Regex(@"^\d{4}-\d{1,2}-\d{1,2}");
            //一年的12个月(01~09和1~12)
            Regex reg = new Regex(@"^(0?[1-9]|1[0-2])$");
            //一个月的31天(01~09和1~31)
            Regex reg = new Regex(@"^((0?[1-9])|((1|2)[0-9])|30|31)$");
            //钱的输入格式:
            //有四种钱的表示形式我们可以接受:”10000.00″ 和 “10,000.00”, 和没有 “分” 的 “10000” 和 “10,000”
            Regex reg = new Regex(@"^[1-9][0-9]*$");
            //这表示任意一个不以0开头的数字,但是,这也意味着一个字符”0″不通过,所以我们采用下面的形式
            Regex reg = new Regex(@"^(0|[1-9][0-9]*)$");
            //一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号
            Regex reg = new Regex(@"^(0|-?[1-9][0-9]*)$");
            //这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分
            Regex reg = new Regex(@"^[0-9]+(.[0-9]+)?$");
            //必须说明的是,小数点后面至少应该有1位数,所以”10.”是不通过的,但是 “10” 和 “10.2” 是通过的
            Regex reg = new Regex(@"^[0-9]+(.[0-9]{2})?$");
            //这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样
            Regex reg = new Regex(@"^[0-9]+(.[0-9]{1,2})?$");
            //这样就允许用户只写一位小数。下面我们该考虑数字中的逗号了,我们可以这样
            Regex reg = new Regex(@"^[0-9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$");
            //1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须
            Regex reg = new Regex(@"^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$");
            //备注:这就是最终结果了,别忘了”+”可以用”*”替代。如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里
            //xml文件
            Regex reg = new Regex(@"^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$");
            //中文字符的正则表达式
            Regex reg = new Regex(@"[\u4e00-\u9fa5]");
            //双字节字符
            Regex reg = new Regex(@"[^\x00-\xff] (包括汉字在内,可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1))");
            //空白行的正则表达式,可用来删除空白行
            Regex reg = new Regex(@"\n\s*\r");
            //HTML标记的正则表达式
            Regex reg = new Regex(@"<(\S*?)[^>]*>.*?</\1>|<.*? />");// (网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力)
            //首尾空白字符的正则表达式
            Regex reg = new Regex(@"^\s*|\s*$或(^\s*)|(\s*$)");// (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式)
            //腾讯QQ号
            Regex reg = new Regex(@"[1-9][0-9]{4,}"); //(腾讯QQ号从10000开始)
            //中国邮政编码
            Regex reg = new Regex(@"[1-9]\d{5}(?!\d)");// (中国邮政编码为6位数字)
            //IP地址
            Regex reg = new Regex(@"\d+\.\d+\.\d+\.\d+");// (提取IP地址时有用)
            //IP地址
            Regex reg = new Regex(@"((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))");

第二章、解决方案(WPF Demo)

       既然第一章提供了正则表达式,那么现在就用正则表达式来解决1.1的问题。

2.1、WPF Demo

 自己建一个WPF工程,把这下面的6个文件添加上去即可(忽略其他样式文件吧)。

  • 页面文件——PacsConfig.xaml(Page类型)和PacsConfig.xaml.cs
  • AETitleVisibilityConverter.cs——判断特殊字符(解决AETitle问题)。
  • IpVisibilityConverter.cs——判断IP(解决IP地址问题)。
  • PortVisibilityConverter.cs——判断端口号(解决端口号问题)。
  • StorageIsStartVisibilityConverter.cs——判断true(1)或false(0)。true则显示“启用”;false则显示“不启用”。
  • 2.1小结中,主要放PacsConfig.xaml(Page类型)和PacsConfig.xaml.cs。
  • 剩下的4个.cs文件,与下面的几个小结一一对应。

 PacsConfig.xaml(用来显示UI):

<Page x:Class="KeenRayLargePC.Views.PacsConfig"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:KeenRayLargePC.Views"
      xmlns:converter="clr-namespace:KeenRayLargePC.VisibilityConverter"
      mc:Ignorable="d" 
      d:DesignHeight="964" d:DesignWidth="1844"
      Title="PacsConfig">

    <Page.Resources>
        <converter:AETitleVisibilityConverter x:Key="textCheckConverter"/>
        <converter:StorageIsStartVisibilityConverter x:Key="enableConverter"/>
        <converter:PortVisibilityConverter x:Key="portConverter"/>
        <converter:IpVisibilityConverter x:Key="ipConverter"/>
    </Page.Resources>

    <Viewbox StretchDirection="Both" Stretch="Fill">
        <Grid Background="#dbdce1" Width="1844" Height="1004">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*" x:Name="column1"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>

            <!--内容-->
            <Canvas Grid.Column="0" Background="#FFF4F4F4" >
                <Border  BorderThickness="1" BorderBrush="#FFA2A2D1" />
                <Label  Content="存储通讯配置" Background="#FFDBDCE1" VerticalAlignment="Center" Width="400"/>
                <TextBox Text="AETitle" Canvas.Left="95" Canvas.Top="56" Height="35" Width="102" Style="{StaticResource CfgTextBoxStyle}" Background="{x:Null}"></TextBox>
                <TextBox Width="444" Height="64" Canvas.Left="267" Canvas.Top="40" VerticalContentAlignment="Center" Name="tbk_StorageAETitle" Text="{Binding StorageAETitle}" Style="{StaticResource TextBoxStyle}" />
                <Label Content="*" Foreground="Red" Canvas.Left="711" Canvas.Top="45" Visibility="{Binding ElementName=tbk_StorageAETitle,Path=Text,Converter={StaticResource textCheckConverter}}" Height="57" Width="38"></Label>

                <TextBox Text="IP地址" Canvas.Left="95" Canvas.Top="159" Height="35" Width="89" Style="{StaticResource CfgTextBoxStyle}" Background="{x:Null}"></TextBox>
                <TextBox Width="444" Height="64" Canvas.Left="267" Canvas.Top="143" VerticalContentAlignment="Center" Name="tbk_StorageIP" Text="{Binding StorageIP}" Style="{StaticResource TextBoxStyle}"/>
                <Label Content="*" Foreground="Red" Canvas.Left="711" Canvas.Top="148" Visibility="{Binding ElementName=tbk_StorageIP,Path=Text,Converter={StaticResource ipConverter}}" Height="57" Width="38"></Label>

                <TextBox Text="端口号" Canvas.Left="95" Canvas.Top="262" Height="35" Width="92" Style="{StaticResource CfgTextBoxStyle}" Background="{x:Null}"></TextBox>
                <TextBox Width="444" Height="65" Canvas.Left="267" Canvas.Top="246" VerticalContentAlignment="Center" Name="tbk_StoragePort" Text="{Binding StoragePort}" Style="{StaticResource TextBoxStyle}"/>
                <Label Content="{Binding ElementName=tbk_StoragePort,Path=Text,Converter={StaticResource portConverter}}" Foreground="Red" Canvas.Left="711" Canvas.Top="251" Height="57" Width="236"></Label>

                <TextBox Text="语法" Canvas.Left="95" Canvas.Top="366" Height="35" Width="62" Style="{StaticResource CfgTextBoxStyle}" Background="{x:Null}"></TextBox>
                <ComboBox Width="444" Height="64" Canvas.Left="267" Canvas.Top="350" VerticalContentAlignment="Center" Style="{StaticResource CfgComboBoxStyle}" IsReadOnly="True" ItemsSource="{Binding StorageGrammar}" SelectedIndex="{Binding StorageGrammarIndex}"/>

                <TextBox Text="发送模式" Canvas.Left="95" Canvas.Top="469" Height="35" Width="123" Style="{StaticResource CfgTextBoxStyle}" Background="{x:Null}"></TextBox>
                <ComboBox Width="444" Height="64" Canvas.Left="267" Canvas.Top="453" VerticalContentAlignment="Center" Style="{StaticResource CfgComboBoxStyle}" IsReadOnly="True" ItemsSource="{Binding SendMode}" SelectedIndex="{Binding SendModeIndex}"/>
                <TextBox Text="是否启用" Canvas.Left="95" Canvas.Top="572" Height="35" Width="123" Style="{StaticResource CfgTextBoxStyle}" Background="{x:Null}"></TextBox>
                <ComboBox Width="444" Height="64" Canvas.Left="267" Canvas.Top="556" VerticalContentAlignment="Center" Style="{StaticResource CfgComboBoxStyle}" IsReadOnly="True" ItemsSource="{Binding IsStorageEnable}" SelectedIndex="{Binding IsStorageEnableIndex}"/>

                <CheckBox Canvas.Left="133" Canvas.Top="675" Content="启动存储确认" Style="{StaticResource CheckBoxStyle}" IsChecked="{Binding IsEnableStorageConfirm}" Height="57" Width="270"></CheckBox>
                <CheckBox Canvas.Left="506" Canvas.Top="675" Content="标注嵌入" Style="{StaticResource CheckBoxStyle}" IsChecked="{Binding IsAnnotationEmbeded}" Height="57" Width="207"></CheckBox>

                <Button Width="150" Height="100" Content="增加" Canvas.Left="76" Canvas.Top="844" Style="{StaticResource StyleButton}" Name="btn_AddStorage" Click="btn_AddStorage_Click"/>
                <Button Width="150" Height="100" Content="修改" Canvas.Left="284" Canvas.Top="844" Style="{StaticResource StyleButton}" Name="btn_ModifyStorage" Click="btn_ModifyStorage_Click"/>
                <Button Width="150" Height="100" Content="删除" Canvas.Left="492" Canvas.Top="844" Style="{StaticResource StyleButton}" Name="btn_DeleteStorage" Click="btn_DeleteStorage_Click"/>
                <Button Width="150" Height="100" Content="测试" Canvas.Left="724" Canvas.Top="844" Style="{StaticResource StyleButton}" Name="btn_TestStorage" Click="btn_TestStorage_Click"/>
            </Canvas>

            <Grid Grid.Column="1" Background="#FFC1C1E3">
                <ListView Grid.Row="0" Style="{StaticResource CfgListViewStyle}" Name="listview_Storage" ItemContainerStyle="{StaticResource ListViewItemContainerStyle}" SelectionChanged="listview_Storage_SelectionChanged" Margin="0,0,0,-14">
                    <ListView.View>
                        <GridView ColumnHeaderContainerStyle="{StaticResource CfgDefaultGridViewColumnHeader}">
                            <GridViewColumn Header="AETitle" Width="200" DisplayMemberBinding="{Binding AETitle}"/>
                            <GridViewColumn Header="IP地址" Width="200" DisplayMemberBinding="{Binding IP}"/>
                            <GridViewColumn Header="端口" Width="200" DisplayMemberBinding="{Binding Port}"/>
                            <GridViewColumn Header="存储启用" Width="200" DisplayMemberBinding="{Binding StorageFlag,Converter={StaticResource enableConverter}}"/>
                        </GridView>
                    </ListView.View>
                </ListView>
            </Grid>

        </Grid>
    </Viewbox>
</Page>

 PacsConfig.xaml.cs(后台逻辑为空,不罗列也罢):

2.2、判断特殊字符(解决AETitle问题)

特别要注意特殊字符 +   -    ?等等,前面一定要加  \\

    class AETitleVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //string str = "[!!@#$%\\^&*()./、~`·\\-_=\\+——><《》\\??]+";
            //string str = "[!!@#$%^&*()./、{}【】~`·-_=+——><《》??]+";
            string str = "[!!@#$%\\^&*()./、{}【】~`·\\-_=\\+——><《》\\??]+";
            Regex regex = new Regex(str);
            if (string.IsNullOrEmpty(value.ToString().Trim()))
            {
                return Visibility.Visible;
            }
            else
            {
                if ((regex.IsMatch(value.ToString())))
                    return Visibility.Visible;
                return Visibility.Hidden;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

2.3、判断IP(解决IP地址问题)

  class IpVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return System.Windows.Visibility.Visible;
            }
            else
            {
                if (string.IsNullOrEmpty(value.ToString()))
                    return System.Windows.Visibility.Visible;
                else
                {
                    string regex = @"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
                    if (!System.Text.RegularExpressions.Regex.IsMatch(value.ToString(), regex))
                    {
                        return System.Windows.Visibility.Visible;
                    }
                }
            }
            return System.Windows.Visibility.Hidden;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

2.4、判断端口号(解决端口号问题)

 public class PortVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToString() == "")
                return "*";
            int port = 0;
            if (Int32.TryParse(value.ToString(), out port))
            {
                if (port > 1024 && port < 65536)
                    return "";
                else
                    return "1025-65535";
            }
            else
            {
                return "1025-65535";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

2.5、判断true或false

    class StorageIsStartVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToString() == "0")
                return "不启用";
            else
                return "启用";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

第三章、实践过程需注意的事项

3.1、验证汉字或中文的正则表达式

        参考https://www.cnblogs.com/feiyucha/p/10051117.html     

       参考了第二章以及网上的几种正则表达式,来验证汉字,都不行。比如:

 Regex reg = new Regex(@"^[\u4e00-\u9fa5]{0,}$");
 Regex reg = new Regex(@"[\u4e00-\u9fa5]{0,}$");
 Regex reg = new Regex("^[\u4e00-\u9fa5]{0,}$");
 Regex reg = new Regex("[\u4e00-\u9fa5]{0,}$");

于是,写成下面的两种形式就可以验证汉字了:

 Regex regex = new Regex("[\u4e00-\u9fa5]");
  • ^ 意思是从字符的起始位置开始匹配,虽然看起来没错,实际却不然。因此我们还是要多多验证才行。
  • 千淘万漉虽辛苦,吹尽狂沙始到金。

完整的Demo如下所示:

#region 正则表达式:费了千辛万苦整理出来的

using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using test;

namespace QueueSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("-----------1:不能用----------");
            CharacterValidity1("我我");
            CharacterValidity1("jj");
            CharacterValidity1("**");
            CharacterValidity1("我我**");
            CharacterValidity1("我我jj");
            CharacterValidity1("**我我");
            CharacterValidity1("jj我我");
            CharacterValidity1("jj**");
            CharacterValidity1("jj我我**");

            Console.WriteLine("-----------2:不能用----------");
            CharacterValidity2("我我");
            CharacterValidity2("jj");
            CharacterValidity2("**");
            CharacterValidity2("我我**");
            CharacterValidity2("我我jj");
            CharacterValidity2("**我");
            CharacterValidity2("jj我");
            CharacterValidity2("jj**");
            CharacterValidity2("jj我**");

            Console.WriteLine("-----------3:不能用----------");
            CharacterValidity3("我我");
            CharacterValidity3("jj");
            CharacterValidity3("**");
            CharacterValidity3("我我**");
            CharacterValidity3("我我jj");
            CharacterValidity3("**我我");
            CharacterValidity3("jj我我");
            CharacterValidity3("jj**");
            CharacterValidity3("jj我我**");

            Console.WriteLine("-----------4:不能用----------");
            CharacterValidity4("我我");
            CharacterValidity4("jj");
            CharacterValidity4("**");
            CharacterValidity4("我我**");
            CharacterValidity4("我我jj");
            CharacterValidity4("**我我");
            CharacterValidity4("jj我我");
            CharacterValidity4("jj**");
            CharacterValidity4("jj我我**");


            Console.WriteLine("-----------5:不能用----------");
            CharacterValidity5("我我");
            CharacterValidity5("jj");
            CharacterValidity5("**");
            CharacterValidity5("我我**");
            CharacterValidity5("我我jj");
            CharacterValidity5("**我我");
            CharacterValidity5("jj我我");
            CharacterValidity5("jj**");
            CharacterValidity5("jj我我**");


            Console.WriteLine("-----------6:不能用----------");
            CharacterValidity6("我我");
            CharacterValidity6("jj");
            CharacterValidity6("**");
            CharacterValidity6("我我**");
            CharacterValidity6("我我jj");
            CharacterValidity6("**我我");
            CharacterValidity6("jj我我");
            CharacterValidity6("jj**");
            CharacterValidity6("jj我我**");

            Console.WriteLine("-----------7:不能用----------");
            CharacterValidity7("我我");
            CharacterValidity7("jj");
            CharacterValidity7("**");
            CharacterValidity7("我我**");
            CharacterValidity7("我我jj");
            CharacterValidity7("**我我");
            CharacterValidity7("jj我我");
            CharacterValidity7("jj**");
            CharacterValidity7("jj我我**");

            Console.WriteLine("-----------8:可以用----------");
            CharacterValidity8("我我");
            CharacterValidity8("jj");
            CharacterValidity8("……………………~~~-----**");
            CharacterValidity8("我我**");
            CharacterValidity8("我我jj");
            CharacterValidity8("**我我***^^^//");
            CharacterValidity8("jj我我");
            CharacterValidity8("jj**");
            CharacterValidity8("jj我我//...**");
            Console.ReadLine();
        }

        //不能用
        private static bool CharacterValidity1(string str)
        {
            bool IsValidity = false;
            Regex regex = new Regex("^[\u4e00-\u9fa5]{0,}$");
            if (regex.IsMatch(str.ToString()))
            {
                IsValidity = true;
            }
            Console.WriteLine(IsValidity.ToString());
            return IsValidity;
        }

        //不能用
        private static bool CharacterValidity2(string str)
        {
            bool IsValidity = false;
            Regex regex = new Regex("^[\u4e00-\u9fa5]{1,}$");
            if (regex.IsMatch(str.ToString()))
            {
                IsValidity = true;
            }
            Console.WriteLine(IsValidity.ToString());
            return IsValidity;
        }

        //不能用
        private static bool CharacterValidity3(string str)
        {
            bool IsValidity = false;
            Regex regex = new Regex("^[\u4e00-\u9fa5]+$");//这是我另一个项目的同事在用,但是我验证了,却是无法用。
            if (regex.IsMatch(str.ToString()))
            {
                IsValidity = true;
            }
            Console.WriteLine(IsValidity.ToString());
            return IsValidity;
        }

        //不能用
        private static bool CharacterValidity4(string str)
        {
            bool IsValidity = false;
            Regex regex = new Regex("[\u4e00-\u9fa5]+$");
            if (regex.IsMatch(str.ToString()))
            {
                IsValidity = true;
            }
            Console.WriteLine(IsValidity.ToString());
            return IsValidity;
        }

        //不能用
        private static bool CharacterValidity5(string str)
        {
            bool IsValidity = false;
            Regex regex = new Regex("[\u4e00-\u9fa5]{0,}$");
            if (regex.IsMatch(str.ToString()))
            {
                IsValidity = true;
            }
            Console.WriteLine(IsValidity.ToString());
            return IsValidity;
        }

        //不能用
        private static bool CharacterValidity6(string str)
        {
            bool IsValidity = false;
            Regex regex = new Regex("[\u4e00-\u9fa5]{1,}$");
            if (regex.IsMatch(str.ToString()))
            {
                IsValidity = true;
            }
            Console.WriteLine(IsValidity.ToString());
            return IsValidity;
        }

        //不能用
        private static bool CharacterValidity7(string str)
        {
            bool IsValidity = false;
            Regex regex = new Regex("[\u4e00-\u9fa5]{0,}");
            if (regex.IsMatch(str.ToString()))
            {
                IsValidity = true;
            }
            Console.WriteLine(IsValidity.ToString());
            return IsValidity;
        }

        //可以用
        private static bool CharacterValidity8(string str)
        {
            bool IsValidity = false;
            Regex regex = new Regex("[\u4e00-\u9fa5]");
            if (regex.IsMatch(str.ToString()))
            {
                IsValidity = true;
            }
            Console.WriteLine(IsValidity.ToString());
            return IsValidity;
        }
    }
}
#endregion

输出结果:

-----------1:不能用----------
True
False
False
False
False
False
False
False
False
-----------2:不能用----------
True
False
False
False
False
False
False
False
False
-----------3:不能用----------
True
False
False
False
False
False
False
False
False
-----------4:不能用----------
True
False
False
False
False
True
True
False
False
-----------5:不能用----------
True
True
True
True
True
True
True
True
True
-----------6:不能用----------
True
False
False
False
False
True
True
False
False
-----------7:不能用----------
True
True
True
True
True
True
True
True
True
-----------8:可以用----------
True
False
False
True
True
True
True
False
True

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我爱AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值