使用正则表达式检查 Word 宏中的数值 [英] Check for Numeric Value in Word Macro using Regular Expressions

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

问题描述

是否可以在 Word 宏中直接使用正则表达式?

Is it possible to directly use regular expressions in Word macros?

我想检查一个字符串是否只包含数字并且以下代码不起作用.

I want to check if a string contains only numbers and the following code does not work.

isNumber = RegEx.IsMatch("234", "[0-9]+$")

我只需要它返回真或假.

I simply need it to return true or false.

推荐答案

您可以在代码中创建 VBScript.Regexp 对象的实例,但更简单的解决方案是使用现有的 VBA函数 IsNumeric.两种方法都包括在下面:

You can create an instance of the VBScript.Regexp object within your code, but an easier solution would be to use the existing VBA function IsNumeric. Both methods are included below:

Sub testNumeric()

    'Use IsNumeric
    MsgBox (IsNumeric("12345"))     'Returns true
    MsgBox (IsNumeric("123a"))      'Returns false

    'Alternatively, using Regexp Object
    Dim regexp
    Set regexp = CreateObject("VBScript.Regexp")
    regexp.Pattern = "[0-9]+$"
    MsgBox (regexp.test("12345"))   'Returns true
    MsgBox (regexp.test("123a"))   'Returns false

End Sub

请注意,正则表达式模式不会严格返回数字,还会返回任何以数字结尾的字符串(即测试a123"返回 true).为了使正则表达式检查严格为数字,模式可以是 ^[0-9]+$.感谢@mike 指出这一点.

Note that the regex pattern does not strictly return numbers, but also any string that ends with numbers (i.e. testing "a123" returns true). To make the regex check strictly numeric, the pattern could be ^[0-9]+$. Thanks to @mike for pointing this out.

这篇关于使用正则表达式检查 Word 宏中的数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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