• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

正则表达式Regex类常用方法

c# 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

1、 IsMatch()方法,IsMatch()方法实际上是一个返回Bool值得方法,如果测试字符满足正则表达式返回True否则返回False。

例子:

//匹配的正则表达式,去掉@不影响效果Regex r = new Regex(@"^[0-9]");//开始匹配Match m = r.Match(this.textBox1.Text);while (m.Success){       MessageBox.Show("首位是数字");       return;}

检测textBox1中输入的值,首位是不是数字。

小注:

1、IsMatch()方法;IsMatch()方法实际上是一个返回Bool值得方法,如果测试字符满足正则表达式返回True否则返回False。

2、@符是用来原样输出的@"",两个引号中间的内容会原样输出,不管其中有什么特殊符号。

2、Replace()方法,Replace()方法实际上是一种替换的方法,替换匹配正则表达式匹配模式。

例子:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;namespace TestRegularExpressions{    class Program    {        static void Main(string[] args)       {            string RegularText = "\\w{1,}@\\w{1,}\\.";            string groupEmail = "[email protected]";            if (Regex.IsMatch(groupEmail,RegularText))            {                Console.WriteLine(Regex.Replace(groupEmail, "@", "==="));            }            else            {                Console.WriteLine("未匹配成功!");            }            Console.ReadKey();        }    }}

输出:

3、Sp本文来源gaodai$ma#com搞$代*码*网(lit()方法,Split()方法实际上是拆分的方法,根据匹配正则表达式进行拆分储存在字符串数组中。

例子:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;namespace TestRegularExpressions{    class Program    {        static void Main(string[] args)        {            string RegularText = ";";            string groupEmail = "[email protected];[email protected];[email protected];[email protected];";            string[] Email;            Email = Regex.Split(groupEmail, RegularText);            foreach (string personEmail in Email)            {                Console.WriteLine(personEmail);            }            Console.ReadKey();        }    }}

输出:

小注:

对于string即字符串,可以使用String.Split 方法,效果一样。例如,去除vsNt中的英文,代码如下:

string[] Au=vsNt.Split(',');

函数具体细节:点击打开链接

Split函数小封装:

        #region 根据pattern拆分字符串        /// <summary>        /// 根据pattern拆分字符串        /// </summary>        /// <param name="input">待拆分的字符串</param>        /// <param name="pattern">拆分标识符</param>        /// <returns>拆分后数组</returns>        private string[] SplitString(string input, string pattern)        {            string[] Email;            Email = Regex.Split(input, pattern);            return Email;        }        #endregion

以上就是正则表达式Regex类常用方法 的内容,更多相关内容请关注搞代码(www.gaodaima.com)!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:正则表达式Regex类常用方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址