2013-12-19 50 views
-2

我有麻烦使用正则表达式来测试一个字符串是否可以接受,如果不显示消息。我检查了教程,并找到了这一个,但它总是返回true,无论字符串是否匹配。为什么test.regex总是返回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" 

也返回:真

我尝试添加

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

但它不工作,我总是得到确定。 代码有什么问题? 如何解决它?

同样的事情发生在我自己的代码中。

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

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 

由于提前, ž

+0

你的代码没有意义。 'regex.Test'不存在,你正在检查'Sub'的返回值。 –

+0

'GetRegEx'这是什么 – sam092

+0

我说我的代码是不同的,并且在我的代码中存在'regex.Test'。第一部分是完整的教程,我想从中理解这些功能。 – ZZA

回答

1

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

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

testpattern = "[0-9]{1,3}"应该pattern = "[0-9]{1,3}"代替

同样,你有stringtotestinputstring。改变这一点以及

+0

你是对的! 我以为这个教程会按照它的方式工作,并且无法弄清楚。现在我将根据这个重写自己的代码,因为这很好。 谢谢。 – ZZA

+0

为了避免同样的错误,我建议养成在使用前声明变量的习惯。这可以通过添加Option Option来强制执行 – sam092