SQL 脚本的正则表达式前瞻/后视匹配 [英] Regex lookahead/lookbehind match for SQL script

查看:42
本文介绍了SQL 脚本的正则表达式前瞻/后视匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试分析一些用于代码质量测试的 SQLCMD 脚本.我的正则表达式没有按预期工作:

I'm trying to analyse some SQLCMD scripts for code quality tests. I have a regex not working as expected:

^(\s*)USE (\[?)(?<![master|\$])(.)+(\]?)

我正在尝试匹配:

  1. 以 USE 开头的字符串(忽略空格)
  2. 后跟可选的方括号
  3. 后跟 1 个或多个非空白字符.
  4. 除非该文本为master"(不区分大小写)
  5. OR 除了该文本是 $ 符号

预期结果:

USE [master] - 不匹配

USE [$(CompiledDatabaseName)] - 不匹配

USE [anything_else.01234] - 匹配

此外,上述相同的模式没有 [] 字符.

Also, the same patterns above without the [ and ] characters.

我使用 Sublime Text 2 作为我的 RegEx 搜索工具并引用了这个 cheatsheet

I'm using Sublime Text 2 as my RegEx search tool and referencing this cheatsheet

推荐答案

你的模式 - ^(\s*)USE (\[?)(?<![master|\$])(.)+(\]?) - 如果您修复其中的字符类问题(即替换 [...](...) 表示 $ 的替代列表或字符序列 master),因此在 Boost 正则表达式中无效.您的 (.)+ 捕获是错误的,因为该组将只包含捕获的最后一个字符(您可以使用 (.+)),但这也匹配空格(而您需要 1 个或多个非空白字符).?1 次或 0 次 量词,但您说您可能有 2 个左括号和右括号(因此,您需要一个限制量词 {0,2}).

Your pattern - ^(\s*)USE (\[?)(?<![master|\$])(.)+(\]?) - uses a lookbehind that is variable-width (its length is not known beforehand) if you fix the character class issue inside it (i.e. replace [...] with (...) as you mean an alternative list of $ or a character sequence master) and thus is invalid in a Boost regex. Your (.)+ capturing is wrong since this group will only contain one last character captured (you could use (.+)), but this also matches spaces (while you need 1 or more non-whitespace characters). ? is the one or zero times quantifier, but you say you might have 2 opening and closing brackets (so, you need a limiting quantifier {0,2}).

你可以使用

^\h*USE(?!\h*\[{0,2}[^]\s]*(?:\$|(?i:master)))\h*\[{0,2}[^]\s]*]{0,2}

参见正则表达式演示

说明:

  • ^ - Sublime Text 中一行的开始
  • \h* - 可选的水平空格(如果需要匹配换行符,请使用 \s*)
  • USE - 文字区分大小写的字符序列 USE
  • (?!\h*\[{0,2}[^]\s]*(?:\$|(?i:master))) - 一个负面的前瞻确保 USE 后面没有:
    • \h* - 零个或多个水平空白
    • \[{0,2} - 零、一个或两个 [ 括号
    • [^]\s]* - 除 ] 和空格外的零个或多个字符
    • (?:\$|(?i:master)) - $ 或不区分大小写的 master(我们转使用 (?i:...) 结构)
    • 不区分大小写
    • ^ - start of a line in Sublime Text
    • \h* - optional horizontal whitespace (if you need to match newlines, use \s*)
    • USE - a literal case-sensitive character sequence USE
    • (?!\h*\[{0,2}[^]\s]*(?:\$|(?i:master))) - a negative lookahead that makes sure the USE is NOT followed with:
      • \h* - zero or more horizontal whitespace
      • \[{0,2} - zero, one or two [ brackets
      • [^]\s]* - zero or more characters other than ] and whitespace
      • (?:\$|(?i:master)) - either a $ or a case-insensitive master (we turn off case sensitivity with (?i:...) construct)

      这篇关于SQL 脚本的正则表达式前瞻/后视匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆