在正则表达式中查找VBA吗? [英] Lookbehind on regex for VBA?

查看:395
本文介绍了在正则表达式中查找VBA吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在VBA正则表达式中进行消极和积极的回溯?

Is there a way to do negative and positive lookbehind in VBA regex?

如果字符串以"A"开头,我不希望匹配,因此我目前正在模式开头执行^ A,然后删除match(0)的第一个字符.显然不是最好的方法!

I want to not match if the string starts with "A", so I am currently doing ^A at the start of the pattern, then removing the first character of match(0). Obviously not the best method!

我正在使用regExp对象.

I am using the regExp object.

推荐答案

VBA提供正向和负向先行,但始终不会落后.

VBA offers positive and negative lookaheads but rather inconsistently not lookbehind.

我所见过的将Regex与VBA一起使用的最佳示例是

The best example of using Regex with VBA that I have seen is this article by Patrick Matthews

[使用Execute而不是Replace的更新示例]

[Updated example using Execute rather than Replace]

虽然我对您的用法尚不完全清楚,但您可以将类似的功能与

While I am not completely clear on your usage you could use a function like this with

  • 跳过任何以A开头的单词
  • 对于不是以a开头的所有单词,它将返回从第二个字符开始的所有内容(使用子匹配-()内的模式为子匹配1-

  • skips any words starting with A
  • for all words not starting with a it returns everything from the second character on (using a submatch - the pattern inside ( and ) is submatch 1 -

Sub TestString()
MsgBox ReducedText("cfat dcat")
MsgBox ReducedText("Sat all over the hat again")
End Sub


Function ReducedText(strIn As String) As String
Dim objRegex As Object
Dim objRegMC As Object
Dim objRegM As Object
Dim strOut As String
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
  .IgnoreCase = True
  'not needed if matching the whole string
  .Global = True
  .Pattern = "\b[^a\s]([a-z]+)"
  If .test(strIn) Then
      Set objRegMC = .Execute(strIn)
      For Each objRegM In objRegMC
        strOut = strOut & objRegM.submatches(0) & vbNewLine
      Next
      ReducedText = strOut
  Else
    ReducedText = "Starts with A"
  End If
End With
End Function

这篇关于在正则表达式中查找VBA吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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