回顾 VBA 的正则表达式? [英] Lookbehind on regex for VBA?

查看:31
本文介绍了回顾 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 结合使用的最佳示例是 这篇文章 作者:Patrick Matthews

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 = "[^as]([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天全站免登陆