用于匹配特定词或其组合以及例外词的正则表达式

Regex for matching specific words or their combination as well as the exception word

我想按照这样的模式查看源代码脚本:

'DELETE' 或 'FROM' 或 'DELETE FROM' 后跟一个 space 后跟任何未跟另一个由点分隔的单词,除了单词 'DUAL'

类似

'(DELETE|FROM|DELETE FROM) \w+', where \w+ != DUAL
but not
'(DELETE|FROM|DELETE FROM) \w+\.\w+'

例子

text fragment desired result
begin DELETE tbl1; DELETE tbl1
select FROM tbl2) loop FROM tbl2
fnc(); DELETE FROM tbl3 where DELETE FROM tbl3
qqq DELETE DUAL; www
eee FROM DUAL rrr
ttt DELETE FROM DUAL where
yy DELETE sch1.tbl1; uuu
iii FROM sch2.tbl2 ooo
ppp DELETE FROM sch3.tbl3 aaa

我的猜测

(FROM|DELETE( FROM)?) (?!DUAL)(?!\w+\.)\w+

第 1 部分匹配太多。第二部分(space 之后)是否正确?

你可能会用到

\b(?>DELETE(?: FROM)?|FROM) (?!DUAL\b)\w+\b(?!\.)

模式匹配:

  • \b 单词边界以防止部分单词匹配
  • (?>DELETE(?: FROM)?|FROM) 原子组(无回溯)以匹配带有可选 FROM 的 DELETE 或仅匹配 FROM
  • (?!DUAL\b) 否定先行断言 DUAL 不是紧跟在单词边界右侧的单词
  • \w+\b 数学1+单词字符和单词边界
  • (?!\.) 否定前瞻,断言不是当前位置右边的点

.NET Regex demo