zoukankan      html  css  js  c++  java
  • 正则表达式中的反向预搜索和正向预搜索的使用方法

    表达式

    方向

    说明

    (?=xxx)

    正向预搜索(向右)

    正向预搜索,判断当前位置右侧是否能匹配指定表达式

    (?!xxx)

    正向预搜索否定,判断当前位置右侧是否不能够匹配指定表达式

    (?<=xxx)

    反向预搜索(向左)

    反向预搜索,判断当前位置左侧是否能够匹配指定表达式

    (?<!xxx)

    反向预搜索否定,判断当前位置左侧是否不能够匹配指定表达式

    预搜索分两种,一种是向右,另外一种是向左,

    以下是各个表达式在.net中的使用例子:

    1.向右肯定搜索:

    string rega = @"(?=[^1-9]\d+)";

    string test="1t2t5";

    MatchCollection mc= Regex.Matches(test,rega);

    此时返回的结果集中包含 2,5.

    2.向右否定搜索:

    string regb = @"(?![^1-9])(\d+)";

    string test="1t2t5";

    MatchCollection mc= Regex.Matches(test,regb);

    此时返回的结果集中包含 1,2,5.

    3.向左肯定搜索:

    string regb = @"(?<=[^1-9])(\d+)";

    string test="1t2t5";

    MatchCollection mc= Regex.Matches(test,regb);

    此时返回的结果集中包含 2,5

    4.向左否定搜索:

    string regb = @"(\d+)(?<![^1-9])";

    string test="1t2t5";

    MatchCollection mc= Regex.Matches(test,regb);

    此时返回的结果集中包含 1,2,5

    不知道为什么,当(\d+)在向左反向预搜索表达式右边时,返回的结果集元素会少一位 ,思考中.

  • 相关阅读:
    [LeetCode] 55. Jump Game 跳跃游戏
    [LeetCode] 163. Missing Ranges 缺失区间
    [LeetCode] 228. Summary Ranges 总结区间
    获取当时时间和日期
    响应式布局设备分界点
    html5shiv.js分析-读源码之javascript系列
    建站模板开源代码
    js 调试问题
    transform使用参考指南
    浏览器版本过低
  • 原文地址:https://www.cnblogs.com/AndyGe/p/2426285.html
Copyright © 2011-2022 走看看