正则表达式在 vb6 中的使用 [英] Usage of RegEx in vb6
问题描述
我需要验证一个字符串,它可能包含字母数字和特殊字符,因为我必须传递只有 Alpha 字符的字符串(不允许使用数字或任何其他特殊字符)
I need to validate a string, which might contain alphanumeric as well as special character, where as I have to pass the one which has only Alpha chars (no numbers or any other special characters are allowed)
在当前的方法中,我使用 ASCII 数字来评估每个字符是否为字母.有没有其他有效的方法来发现字符串中是否存在特殊字符或数字?就像我们不能使用 Like 或其他东西来检查一次而不是逐个字符地检查吗?
In a current method I use ASCII numbers to evaluate each character if its alpha or not. Is there any other efficient way to discover the presence of special characters or numbers in the string? Like can't we use Like or something to check once than going character by character?
For y = 2 To Len(sString)
If Not ((Asc(Mid$((sString,y,1))>64 AND Asc(Mid$((sString,y,1))<91) OR _
(Asc(Mid$((sString,y,1))>96 AND Asc(Mid$((sString,y,1))<123)) Then
//Display an error msg
Exit For
End If
Next y
推荐答案
您可以在 VB6 中使用正则表达式.您必须向您的项目添加对Microsoft VBScript 正则表达式 5.5"库的引用.然后,您可以使用以下内容:
You can use regular expressions in VB6. You have to add a reference to the "Microsoft VBScript Regular Expressions 5.5" library to your project. You can then use the following:
Dim rex As RegExp
Set rex = New RegExp
rex.Pattern = "[^a-zA-Z]"
If rex.Test(s) Then
' Display error message
End If
当我最初回答这个问题时,它被标记为 VB.NET;为了将来参考,我原来的基于 .Net 的答案保留在下面
如您所想,这可以通过正则表达式来完成(不要忘记 Imports System.Text.RegularExpressions
:
As you thought, this can be done with regular expressions (don't forget Imports System.Text.RegularExpressions
:
If Regex.IsMatch(s, "[^a-zA-Z]") Then
' Display error msg
End If
另外,原始代码读起来像 VB6 代码,而不是 VB.NET.这是编写原始非正则表达式代码的一种更具可读性的方法:
Also, the original code reads like VB6 code, not VB.NET. Here is a much more readable way to write the original non-regex code:
For Each ch As Char In someString
If Not (ch >= "a"c AndAlso ch <= "z"c OrElse ch >= "A"c AndAlso ch <= "Z"c) Then
' Display error msg
Exit For
End If
Next
这篇关于正则表达式在 vb6 中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!