特殊字符的 VBA 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26763594/
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
VBA RegExp for Special Characters
提问by
When a user enters a "save as" name for the output from my Macros, I want to check for special characters that will cause an error in saving a file - [\/:*?<>|]
当用户为我的宏的输出输入“另存为”名称时,我想检查会导致保存文件错误的特殊字符 - [\/:*?<>|]
I'm using RegExp like so:
我像这样使用 RegExp:
Dim regEx As New RegExp
Dim strSpecChar As String: strSpecChar = "*[\/:*?<>|]*" 'Compile Error here
Dim OutputFileName As String: OutputFileName = InputBox("Enter File Name")
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strSpecChar
End With
If regEx.Test(OutputFileName) Then
'error msg
End If
I'm getting Compile Error: Invalid Character
error because of the bar (|
) character. I've tried escaping bar with backslash but it doesn't work. Can someone help? I've read a couple posts including this onebut it hasn't helped.
Compile Error: Invalid Character
由于 bar ( |
) 字符,我收到错误消息。我试过用反斜杠转义 bar 但它不起作用。有人可以帮忙吗?我读过几篇文章,包括这篇文章,但没有帮助。
SOLUTION:Take a look at blog.tkacprow.pl
's comment below and Alex
's answer (he helped point out a typo and explains error 5018. Remove *
from the strSpecChar variable above.
解决方案:看看blog.tkacprow.pl
下面的评论和Alex
答案(他帮助指出了一个错字并解释了错误 5018。*
从上面的 strSpecChar 变量中删除。
采纳答案by Alex
Did not check if your regexp is correct, but you have included the character "
in the regexp, which vba treated it as end of string. You could use chr (34) to replace the double quote:
没有检查您的正则表达式是否正确,但是您已将字符包含"
在正则表达式中,vba 将其视为字符串的结尾。您可以使用 chr (34) 替换双引号:
strSpecChar = "*[\/:*?" & Chr(34) & "<>]|*"
回答by Ron Rosenfeld
There's really no need to use the Regular Expression engine to just test of the existence of one of a group of characters in the string. You can simply use the VBA Like Operator, to accomplish the same task, with no need of referencing an external library:
真的没有必要使用正则表达式引擎来测试字符串中一组字符中的一个是否存在。您可以简单地使用 VBA Like Operator 来完成相同的任务,而无需引用外部库:
Const strSpecChar As String = "*[\/:*?<>|]*"
Dim OutputFileName As String: OutputFileName = InputBox("Enter File Name")
If OutputFileName Like strSpecChar Then
MsgBox "Error Message"
End If
Or, if you want to include the double quote as one of the characters to be excluded:
或者,如果要将双引号包含为要排除的字符之一:
Const strSpecChar As String = "*[\/:*?<>|""]*"
Note the use of the doubled double quote within the character class, so as to tell VBA to include that rather than mark the end of the string.
请注意在字符类中使用双引号,以便告诉 VBA 包含它而不是标记字符串的结尾。