C#正则表达式-单词边界

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


namespace _05单词边界
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 字符串\b的作用 (\b{0}\b)=> 左\b 表示左边匹配不到单词,向右可以匹配到单词,是单词边界
                                            //=> 右\b 表示右边匹配不到单词字符,向左边可以匹配到单词字符,是单词边界
                                            // \btest\b相当于 test的左右两边都不为[a-zA-Z0-9_]时为单词边界
            /*
             将单词row 替换成单词line 并不是用字符串row 替换成line
             */
            string msg = @"tomorrow.the row we are looking for is. row number 10";
            // \b:表示单词的边界 (只判断不匹配-断言)
            //msg = msg.Replace("row", "line");  =>字符串替换
            msg = Regex.Replace(msg, @"\brow\b","line");  //=>单词替换
            Console.WriteLine(msg);


            /*
             将三个字符组成的单词提取出来
             */
            //string msg2 = @"Hi! where are you from ? I from china";
            string msg2 = @"Hi! where#are#you#from ? I from china";
            MatchCollection matchs = Regex.Matches(msg2, @"\b[a-zA-Z]{3}\b");
            foreach (Match item in matchs)
            {
                Console.WriteLine(item.Value);
            }

            /*
             提取###
             匹配到0个 \b只能匹配单词字符[a-zA-Z0-9_] =》\w
             */
            string msg3 = @"### ## # ##### ### ## #######";
            MatchCollection matchs2 = Regex.Matches(msg3, @"\b###\b");
            //MatchCollection matchs2 = Regex.Matches(msg3, @"(?<= )###(?= )");


            foreach (Match item in matchs2)
            {
                Console.WriteLine(item.Value);
            }


           /*
            (?<=aa){0}(?=bb)断言 字符串左边为aa右边为bb时匹配正则
             */
            #endregion
            Console.ReadKey();
        }
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值