关键词搜索

源码搜索 ×
×

正则表达式Regex类常用方法

发布2014-01-08浏览2489次

详情内容

1、 IsMatch()方法,IsMatch()方法实际上是一个返回Bool值得方法,如果测试字符满足正则表达式返回True否则返回False。
例子:
  1. //匹配的正则表达式,去掉@不影响效果
  2. Regex r = new Regex(@"^[0-9]");
  3. //开始匹配
  4. Match m = r.Match(this.textBox1.Text);
  5. while (m.Success)
  6. {
  7. MessageBox.Show("首位是数字");
  8. return;
  9. }
检测 textBox1中输入的值,首位是不是数字。
小注:
1、IsMatch()方法;IsMatch()方法实际上是一个返回Bool值得方法,如果测试字符满足正则表达式返回True否则返回False。
2、 @符是用来原样输出的@"",两个引号中间的内容会原样输出,不管其中有什么特殊符号。
2、Replace()方法,Replace()方法实际上是一种替换的方法,替换匹配正则表达式匹配模式。
例子:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. namespace TestRegularExpressions
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. string RegularText = "\\w{1,}@\\w{1,}\\.";
  13. string groupEmail = "111@126.com";
  14. if (Regex.IsMatch(groupEmail,RegularText))
  15. {
  16. Console.WriteLine(Regex.Replace(groupEmail, "@", "==="));
  17. }
  18. else
  19. {
  20. Console.WriteLine("未匹配成功!");
  21. }
  22. Console.ReadKey();
  23. }
  24. }
  25. }
输出:
3、Split()方法,Split()方法实际上是拆分的方法,根据匹配正则表达式进行拆分储存在字符串数组中。
例子:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. namespace TestRegularExpressions
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. string RegularText = ";";
  13. string groupEmail = "111@126.com;222@126.com;333@126.com;444@126.com;";
  14. string[] Email;
  15. Email = Regex.Split(groupEmail, RegularText);
  16. foreach (string personEmail in Email)
  17. {
  18. Console.WriteLine(personEmail);
  19. }
  20. Console.ReadKey();
  21. }
  22. }
  23. }
输出:
小注:
        对于string即字符串,可以使用String.Split 方法,效果一样。例如,去除vsNt中的英文,代码如下:
string[] Au=vsNt.Split(',');
        函数具体细节: 点击打开链接
Split函数小封装:
  1. #region 根据pattern拆分字符串
  2. /// <summary>
  3. /// 根据pattern拆分字符串
  4. /// </summary>
  5. /// <param name="input">待拆分的字符串</param>
  6. /// <param name="pattern">拆分标识符</param>
  7. /// <returns>拆分后数组</returns>
  8. private string[] SplitString(string input, string pattern)
  9. {
  10. string[] Email;
  11. Email = Regex.Split(input, pattern);
  12. return Email;
  13. }
  14. #endregion



 
 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载