正则表达式,如果前面带有not或no,则排除

时间:2016-11-22 19:29:16

标签: sql regex oracle regex-negation

我如何编写正则表达式来查找单词bad,其中没有单词not not或no。

在下面的示例中,我应该找到第1行和第4行。

Line 1: a bad rider

Line 2 : apple is not bad

Line 3 : there is no bad remarks.

Line 4  : no there  is nothing bad

是否可以在没有预见的情况下执行此操作,因为Oracle sql不支持它。

2 个答案:

答案 0 :(得分:0)

我相信这可能会让你更接近并允许“不”或“坏”是另一个词的一部分。正则表达式查找一个空格,后跟字符串“not”或“no”后跟一个空格,然后是“bad”,后跟一个空格或行的结尾(确保它们不是另一个单词的一部分)。添加更多测试短语,直到您确定!即,您是否需要允许特殊字符,例如第5行是否以问号结尾?

SQL> with tbl(data) as (
  2    select 'Line 1: a bad rider' from dual union
  3    select 'Line 2 : apple is not bad' from dual union
  4    select 'Line 3 : there is no bad remarks.' from dual union
  5    select 'Line 4 : no there is nothing bad' from dual union
  6    select 'Line 5 : was that knot bad' from dual union
  7    select 'Line 6 : let''s play badminton' from dual union
  8    select 'Line 7 : let''s play no badminton' from dual
  9  )
 10  select *
 11  from tbl
 12  where not regexp_like(data, ' (not|no) bad( |$)');

DATA
---------------------------------
Line 1: a bad rider
Line 4 : no there is nothing bad
Line 5 : was that knot bad
Line 6 : let's play badminton
Line 7 : let's play no badminton

SQL>

答案 1 :(得分:-1)

尝试:

select *
from table
where regexp_like( column, 'bad' ) and NOT regexp_like( column, '(not|no) bad' )

或者只是(可能是最快的):

select *
from table
where  column like( '%bad%' ) 
  and not (column like '%not bad%' or column like '%no bad%');