使用VBA正则表达式识别不包含特定单词的字符串

时间:2016-01-14 22:42:05

标签: regex excel vba excel-vba

使用VBA Regular Expresions,我试图在Excel中找到包含字符串" CK"并且不包含字符串" AS",但它会阻止以A或S开头的任何字符串。我使用以下表达式:

pattern1 = "^[^AS](.*)CK(.*)" 

我已经看到了建议的负向前瞻,但我所见过的所有建议的表达(主要是针对其他编程语言)都没有与VBA-Excel一起使用。

任何提示?

2 个答案:

答案 0 :(得分:1)

没有断言就可以这样做(但这很难):

'the idea is that it should contain CK but it should not contain AS in the very beginning'

^(?:A[^SC].*CK|AC[^K].*CK|ACK|CK|[^A].*CK).*$

格式化

 ^ 
 (?:
      A [^SC] .* CK 
   |  
      AC [^K] .* CK 
   |  
      ACK 
   |  
      CK
   |  
      [^A] .* CK 
 )
 .* 
 $

或者,AS不在字符串中的任何位置

^(?:[^A]|A[^S])*(?:ACK|CK)(?:[^A]|A(?:[^S]|$))*$

格式化

 ^   
 (?:
      [^A] 
   |  
      A 
      [^S] 
 )*
 (?:
      ACK
   |  
      CK
 )
 (?:
      [^A] 
   |  
      A 
      (?: [^S] | $ )
 )*
 $

答案 1 :(得分:1)

尝试这种模式

^(?!AS).*CK.*

(?!AS)AS的否定前瞻,其中(?! )由VBA提供给负前瞻。请注意,相比之下,VBA不提供lookbehinds。阅读更多:

https://www.regular-expressions.info/vbscript.html

https://www.regular-expressions.info/lookaround.html#lookahead

相关问题