如何使用正则表达式匹配 VBA 中的简单数字模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4809453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to match a simple number pattern in VBA using RegEx
提问by JOE SKEET
How do I check if a string is either a one digit number OR a two digit number and otherwise return false
?
如何检查字符串是一位数字还是两位数字,否则返回false
?
回答by Fionnuala
How about:
怎么样:
Function OneOrTwo(i As Integer) As Boolean
Dim objRegEx As Object
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
objRegEx.Pattern = "^\d{1,2}$"
OneOrTwo = objRegEx.Test(i)
End Function
回答by Charles Williams
You can also do this using VBA LIKE:
您也可以使用 VBA LIKE 执行此操作:
Function OneOrTwo(Digits As Variant) As Boolean
OneOrTwo = Digits Like "#" Or Digits Like "##"
End Function
回答by Damon Skelhorn
IF CInt(myNumberString) < 100 Then
MsgBox "String must be either 1 or 2 digits"
Else
Msgbox "Failed"
End IF
Should work for you.
应该为你工作。
回答by aevanko
Remou had it right. Here is a RegexContains function so you can use it with all sorts of patterns, not just the one you need now.
雷穆说得对。这是一个 RegexContains 函数,因此您可以将它用于各种模式,而不仅仅是您现在需要的模式。
Function RegexContains(ByVal find_in As String, _
ByVal find_what As String, _
Optional IgnoreCase As Boolean = False) As Boolean
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = find_what
RE.IgnoreCase = IgnoreCase
RE.Global = True
RegexContains = RE.Test(find_in)
End Function
Following the example from Remou, assuming the cell is A1, you'd write:
按照 Remou 的示例,假设单元格为 A1,您将编写:
=RegexContains(A1, "^\d{1,2}$")
=RegexContains(A1, "^\d{1,2}$")
回答by Lee Louviere
Here is what I would try. /d for digit, ? for option 2 digits.
这是我会尝试的。/d 代表数字,? 对于选项 2 位数字。
/d/d?
/日/日?
or
或者
/d{1,2}
/d{1,2}