【问题标题】:regex get string within two string正则表达式在两个字符串中获取字符串
【发布时间】:2016-02-14 22:03:06
【问题描述】:

我有一个查询,想获取from & where 之间的表名 如果它是没有别名的单行单表,我可以这样做:

(?<=from )([^#]\w*)(?=.*where)

我需要获取除前缀表之外的每个表。即course cmarks s

但我无法找出以下查询的正则表达式。 where 子句可以在同一行或新行,在行首或带有空格或制表符)

from #prefix#student, course c, marks m
where .... 

有些地方也有子查询,如果这种情况也能处理会有所帮助。

select ... from course c
where id = (select ... from student where ...)

我正在尝试在sublime text 3 编辑器中查找和替换

测试用例查询:

//output [course]
select ... from course
where ...

//output [course c] [marks s]    
select ... from course c, marks s
where ....

//output [marks m]  
select ... from #prefix#course c, marks m
where ...

//output [student s]  
select ... from #prefix#course c
where id = (select ... from student s where ...)

【问题讨论】:

  • 你的预期输出是什么?
  • @AvinashRaj 我已经编辑了问题,请检查。我需要获取所有表名,以便替换它们
  • 不确定,但我想你可以试试\bfrom([^w]*(?:\bw(?!here\b)[^w]*)*)where
  • 如果不想在from之后匹配任何以#开头的子字符串,我宁愿使用\bfrom(?!\s*#)([^w]*(?:\bw(?!here\b)[^w]*)*)where
  • @Bsienn 感谢您的回答!我的正则表达式正好相反。排除子查询中的表名。最好尽可能准确地描述问题。

标签: regex sublimetext3


【解决方案1】:

您可以使用以下正则表达式:

\bfrom\b(?!\s*#)([^w]*(?:\bw(?!here\b)[^w]*)*)\bwhere\b

regex demo

勾选区分大小写选项以备不时之需。

如果您只需要突出显示 fromwhere 之间的所有内容,请使用环视:

(?<=\bfrom\b)(?!\s*#)([^w]*(?:\bw(?!here\b)[^w]*)*)(?=\bwhere\b)

查看another demo 和显示结果的屏幕:

正则表达式分解:

  • (?&lt;=\bfrom\b) - 检查下一个之前是否有整个单词from...
  • (?!\s*#) - 确保没有 0 个或多个空格后跟 #
  • ([^w]*(?:\bw(?!here\b)[^w]*)*) - 匹配任何不是where 的文本,直到...
  • (?=\bwhere\b) - 一个完整的词where

更新

由于您需要获取逗号分隔的值(不包括带有别名的前缀名称),因此您需要一个边界约束的正则表达式。可以通过\G操作符实现:

(?:\bfrom\b(?:\s*#\w+(?:\s*\w+))*+|(?!^)\G),?\s*\K(?!(?:\w+ )?\bwhere\b)([\w ]+)(?=[^w]*(?:\bw(?!here\b)[^w]*)*\bwhere\b)

这里,

  • (?:\bfrom\b(?:\s*#\w+(?:\s*\w+))*+|(?!^)\G) - 匹配 from(作为一个完整的单词)后跟可选空格,后跟 # 和 1 个或多个字母数字,后跟空格+字母数字(别名)
  • ,?\s*\K - 可选(1 或 0)逗号后跟 0 或多个空格,后跟 \K强制引擎忽略匹配的整个文本块
  • (?!(?:\w+ )?\bwhere\b) - 限制性前瞻,我们禁止下一个或下一个单词之后的单词等于where
  • ([\w ]+) - 我们的匹配项,1 个或多个字母数字或空格(可以替换为 [\w\h]+
  • (?=[^w]*(?:\bw(?!here\b)[^w]*)*\bwhere\b) - 尾随边界:必须有除 where 之外的文本,直到第一个 where

【讨论】:

猜你喜欢
  • 2014-12-08
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
相关资源
最近更新 更多