C#之regular expression

1. 使用正则表达式需引用using System.Text.RegularExpressions;

2. 基本用法

3. 常见的方法:IsMatch()、Replace()、Split()和Match的类

如图,只要在新建regex输入正则表达式即可

4. 匹配数字的例子,例如电话区号

对于IP的匹配则更加复杂,IP字串,由四段组成,每一段是0~255的数字,段与段之间用小数点隔开,比如61.139.2.69就是一个合法的IP字串。

对于三位数 25[0-5] | 2[0-4]d | 1dd,分别对应250到255,200到249,100到199

对于两位数 [1-9]d 十位不为零,对于一位数[1-9]

则对于一个段来说正则表达式为((25[0-5])|(2[0-4]d)|(1dd)|([1-9]d)|d),而二三四段前面都有点,应该为(.((25[0-5])|(2[0-4]d)|(1dd)|([1-9]d)|d)),重复三次即{3}

完整表达式为:((25[0-5])|(2[0-4]d)|(1dd)|([1-9]d)|d)(.((25[0-5])|(2[0-4]d)|(1dd)|([1-9]d)|d)){3}


其他匹配:匹配完整域名的正则表达式:  [a-zA-Z0-9][-a-zA-Z0-9]{0,62}(.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+.?

              匹配时间的有很多格式。。。

5. 补充tryparse和parse:           TryParse 方法类似于 Parse 方法,不同之处在于 TryParse 方法在转换失败时不引发异常

Decimal.TryParse 方法 (String, Decimal) 将字符串数字转化为decimal

Decimal.TryParse 方法 (String, NumberStyles, IFormatProvider, Decimal) : 使用指定样式和区域性特定格式将数字的字符串表示形式转换为其 Decimal 类型。

诸多示例可见

https://msdn.microsoft.com/zh-cn/library/ew0seb73(v=vs.110).aspx

string是要转换的字符串

numberstyles是数字的类型(允许十进制标点,允许money标号如¥$等等)

iformatprovider是指定国家

number是转换后的结果

附例子一则:

// Parse currency value using en-GB culture.
value = "£1,097.63";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-GB");
if (Decimal.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays: 
//       Converted '£1,097.63' to 1097.63.
原文地址:https://www.cnblogs.com/GameChina/p/4438151.html