Word VBA中的正则表达式 [英] Regular Expression in Word VBA
问题描述
我在适用于 MS Word 的 VBA 中有以下正则表达式语法:
I have the following regular expression syntax in VBA for MS Word which works:
regEx.Pattern = "\w*\(\w*\s[0-9]{1,3}:[0-9]{1,3}(\)|\-[0-9]{1,3}\))"
MsgBox regEx.test("This is a test (Chronicles 13:12-14)")
这将根据需要返回 True.当我试图在我的左括号之后包含第一"、第二"、第三"、1、2、3 或什么都不包含的模式时,我遇到了困难.我试过[First|Second|Third|1|2|3]
?但是当我在括号内添加任何这些字符串/数字时,它会返回 false.我错过了什么?
This returns True, as desired. I encounter difficulty when I attempt to include patterns for "First", "Second", "Third", 1, 2, 3, or nothing immediately following my opening parenthesis. I have tried [First|Second|Third|1|2|3]
? but that returns false when I add any of those strings/numbers inside the parenthesis. What am I missing?
感谢您的解释和建议.我添加了最后的|"后面没有任何内容来说明缺少任何数字.我还必须在每个选项中添加空格.最终的工作版本是 "\w*\((第一 |第二 |第三 |[1-3] |)\w*\s[0-9]{1,3}:[0-9]{1,3}(\)|\-[0-9]{1,3}\))"
Thanks for the explanations and suggestion. I added a final "|" without anything after it to account for the lack of any of the numbers. I also had to add spaces in each option. The final working version is
"\w*\((First |Second |Third |[1-3] |)\w*\s[0-9]{1,3}:[0-9]{1,3}(\)|\-[0-9]{1,3}\))"
推荐答案
字符类 ([]
) 匹配任何包含的字符.因此,[First|Second|Third|1|2|3]
匹配 F
, i
, r
>、s
、t
、|
、S
等
Character classes ([]
) match literally any of the contained characters. Because of that, [First|Second|Third|1|2|3]
matches F
, i
, r
, s
, t
, |
, S
, etc.
您需要在字符类之外使用交替.您可以使用 (...)
对其进行分组,或者如果您想要一个非捕获组 (?:...)
.
You'll want to use alternation outside of the character class. You can group this using (...)
or if you want a non-capturing group (?:...)
.
尝试将 [First|Second|Third|1|2|3]
替换为 (?:First|Second|Third|[1-3])
.
这篇关于Word VBA中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!