如何在VBA正则表达式中模拟后向行为? [英] How to simulate lookbehind in VBA regex?

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

问题描述

我正在尝试构建一个正则表达式模式,如果字符串以某些字符开头或包含非单词字符,则该模式将返回False,但是由于VBA的RegExp对象不支持向后看,所以我发现这很困难.唯一应该失败的单词字符前缀是B_,B-,b_,b-.

I'm trying to build a regex pattern that will return False if a string starts with certain characters or contains non-word characters, but because VBA's RegExp object doesn't support lookbehind, I am finding this difficult. The only word character prefixes that should fail are B_, B-, b_, b-.

这是我的测试代码:

Sub testregex()

Dim re As New RegExp

re.pattern = "^[^Bb][^_-]\w+$"

Debug.Print re.Test("a24")
Debug.Print re.Test("a")
Debug.Print re.Test("B_")
Debug.Print re.Test(" a1")


End Sub

我希望它返回:

True
True
False
False

但它返回

True
False
False
True

问题是模式会查找不在[Bb]中的字符,然后是不在[-_]中的字符,然后是一系列字字符,但是我想要的只是一个或多个字字符,这样,如果有2个或更多字符,则前两个不是[Bb][-_].

The problem is that the pattern looks for a character that's not in [Bb], followed by a character that's not in [-_], followed by a sequence of word characters, but what I want is just one or more word characters, such that if there are 2 or more characters then the first two are not [Bb][-_].

推荐答案

尝试匹配此表达式:

^([Bb][\-_]\w*)|(\w*[^\w]+\w*)$

...将与"B _","b _","B-"和"b-"或任何非文字字符匹配的内容.将成功匹配视为失败",并且仅允许不匹配有效.

...which will match "B_", "b_", "B-" and "b-" or anything that's not a word character. Consider a successful match a "failure" and only allow non-matches to be valid.

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

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