VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)
首页 - 经验之谈 - Use regular expressions for VB wildcard string extractions
发表评论(0)作者:不详, 平台:VB6.0+Win98, 阅读:8761, 日期:2001-08-01
Use regular expressions for VB wildcard string extractions

While VB provides several ways to perform string manipulations
and searches, it doesn注释:t always provide the best wildcard search
options. To that end, try using regular expressions, introduced
in VBScript 5.0+, but available for use in VB projects.

Regular expressions let you quickly and concisely search for patterns
within strings, and in most cases perform an action on them. In
its basic form, a regular expression consists of a single or series
of strings, literal or representative. You can then match this
template against a second string or number (as a string). For example,
the literal pattern 注释:abc注释: as a regular expression would find a
match in 注释:dabcef注释:, 注释:abcdef注释: or 注释:defabc注释:. As you might expect, you
can also use a host of special metacharacters to further refine
a regular expression. Visit Microsoft注释:s VBScript documentation
Web site (msdn.microsoft.com/scripting) and then look up the RegExp
in the VBScript Keyword Documentation section to learn more specifics
about these patterns.

To give you a taste of what regular expressions can do, however,
suppose your project accepted input in the following format:

A1234B4567

Under the program注释:s guidelines, there can be any number of digits
between the A and the B, as well as after the B. In your code,
you want to extract the string, including all digits after the
B. To accomplish this task, after setting a reference to the Microsoft
VBScript Regular Expressions 1.0 library, you could use code similar
to:

Private Sub Form_Load()
Dim reg As New RegExp
Dim strTest As String
Dim regPattern As String
Dim Matches As MatchCollection
Dim mtch As Match

Dim blnFound As Boolean

strTest = "A1234B4567"
regPattern = "B\d+$"

With reg
    .Pattern = regPattern
    MsgBox .Test(strTest)
    Set Matches = .Execute(strTest)
    
    For Each mtch In Matches
        MsgBox mtch.Value
    Next mtch
End With
Set reg = Nothing

End Sub

For more information and a tutorial on how to use regular expressions
to validate user data entry, read Inside Microsoft Visual Basic注释:s
August 2001 article "Provide field validation with regular expressions"
(www.elementkjournals.com/ivb/0108/ivb0181.htm).