为什么test.regex总是返回true?

时间:2013-12-19 09:19:03

标签: regex vba

我在使用正则表达式来测试字符串是否可接受以及是否显示消息时遇到了麻烦。我已经检查了教程,并找到了这个,但它总是返回true,无论字符串是否匹配。

Function TestRegEx(regex As Object, testpattern As String, stringtotest As String) As Boolean
Dim regMatch As Object  ' MatchCollection 

With regex 
.Pattern = testpattern 
.MultiLine = False
End With

' match test string against regex string 
Set regMatch = regex.Execute(stringtotest) 
TestRegEx = (regMatch.Count > 0) 
End Function



Sub TestRegex() 
Dim regex As Object  ' RegExp 
Dim pattern As String
Dim inputstring As String

Set regex = GetRegEx 
If Not regex Is Nothing Then
testpattern = "[0-9]{1,3}" ' 1 to 3 numbers 
stringtotest = "12"
MsgBox TestRegEx(regex, pattern, inputstring) 
End If
End Sub

如果我写了其他内容:stringtotest,如:baloon,dog,3333它总是返回True。

testpattern = "^[0-9]{5}$" 
stringtotest = "KB"

同样返回:True

我尝试添加

If TestRegEx(regex, pattern, inputstring) = True Then
msgbox "OK"
Else
msgbox "NotOK"
End IF

但它不起作用,我总是好的。 代码有什么问题? 如何解决?

我自己的代码也会发生同样的事情。

在我的情况下,如果outlook中的邮件主题包含特定字符串,我需要检查。我使用稍微不同的代码,然后是教程,但它永远不会得到假。

regex.pattern = "Cid#\d{4}"

If regex.Test(msg.Subject) = True Then
...
Else
...

修改

Function GetRegEx() As Object
 On Error Resume Next
 Set GetRegEx = CreateObject("VBScript.RegExp")
End Function

我忘记了这一点,抱歉。

我在jpsoftware上找到了这个教程

EDIT2:我的代码

Dim objInsp As Outlook.Inspector
Dim msg As Outlook.MailItem
Dim regex As New RegExp
Dim prevsubj As String


Set objInsp = Application.ActiveInspector
Set msg = objInsp.CurrentItem
prevsubj = msg.Subject
subjlen = Len(prevsubj)


regex.IgnoreCase = False
regex.pattern = "Cid#\d{4}"
Set regex = GetRegEx


If regex.Test(msg.Subject) = True Then

MsgBox regex.Test(msg.Subject)


newtempsubj = Left(prevsubj, subjlen - 8)
msg.Subject = newtempsubj & " Cid#" & 'newidstring
msg.Close olSave
Else

MsgBox prevsubj

msg.Subject = prevsubj & " Cid#" & 'newidstring
msg.Close olSave

End If

提前致谢, ž

1 个答案:

答案 0 :(得分:1)

好。我找到了。一个愚蠢的错误 - 一个错字。

您有一个名为testpattern的变量,另一个名为pattern

testpattern = "[0-9]{1,3}"应为pattern = "[0-9]{1,3}"

同样,您有stringtotestinputstring。改变它