【问题标题】:Regex to exclude substring正则表达式排除子字符串
【发布时间】:2021-02-04 09:02:33
【问题描述】:

我想写正则表达式:

  1. 传递以/scripts/my_app/ 开头的字符串(/scripts/my_app/xxxx.sh 或/scripts/my_app/yyyyy/xxxz.sh)
  2. 排除其他以/scripts/ 开头的字符串(/scripts/another_string/xxxx.sh 或/scripts/some_string/yyyyy/xxxz.sh)
  3. 传递任何其他字符串,例如/xxxx/yyyy/zzzzz/qqqq.sh 或/aaaa/bbbb/ccc.sh

^[(\/scripts\/my_app\/)|(?!\/scripts\/)].* 这样的东西不起作用。

【问题讨论】:

    标签: regex-negation


    【解决方案1】:

    你可以使用

    ^/(?:scripts/my_app/|(?!scripts/)).*
    

    说明

    • ^/ 字符串开头并匹配 /
    • (?:非捕获组
      • scripts/my_app/ 字面匹配
      • |或者
      • (?!scripts/) 负前瞻,不断言 scripts/
    • )关闭非捕获组
    • .* 匹配任意字符 0+ 次

    Regex demo

    另一种选择是使用双重否定前瞻

    ^/(?!scripts/(?!my_app/)).*
    

    Regex demo

    【讨论】:

    • 谢谢!我不知道 (?: Non capture group
    • 第二个选项不能在像 /scripts/my_app_OLD/ 这样的字符串上正常工作 需要添加斜杠 ^/(?!scripts/(?!my_app/)).*
    • @user3441194 啊,应该是^/(?!scripts/(?!my_app/)).*regex101.com/r/ol2SVM/1
    猜你喜欢
    • 2012-02-17
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2021-09-16
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    相关资源
    最近更新 更多