过滤字符串

时间:2012-01-20 23:08:15

标签: vb.net

我有一些字符串,我想通过使用过滤器来查看它们是否包含某些字符。

以下是我所谈论的那种事情的例子......

Dim files() As String = IO.Directory.GetFiles("folder path", filter)

除了基于过滤器获取文件之外,我想通过过滤器检查字符串。过滤器可以包含通配符,必需字符等

希望这有意义......

2 个答案:

答案 0 :(得分:2)

除了RegularExpressions之外,VB.NET提供了另一种 - 易于使用的方式:

Like-Operator

Characters in pattern        Matches in string
          ?                  Any single character
          *                  Zero or more characters
          #                  Any single digit (0–9)
    [ charlist ]             Any single character in charlist
    [! charlist ]            Any single character not in charlist

How to: Match a String against a Pattern (Visual Basic)

MSDN中的一些示例

检查七位数的电话号码phoneNum是否正好有三个数字,后跟空格,连字符( - ),句点(。)或根本没有字符,后面跟着正好四位数字:

Dim sMatch As Boolean = 
  (phoneNum Like "###[ -.]####") OrElse (phoneNum Like "#######")

其他模式:

Dim testCheck As Boolean
' The following statement returns True (does "F" satisfy "F"?)
testCheck = "F" Like "F"
' The following statement returns False for Option Compare Binary
'    and True for Option Compare Text (does "F" satisfy "f"?)
testCheck = "F" Like "f"
' The following statement returns False (does "F" satisfy "FFF"?)
testCheck = "F" Like "FFF"
' The following statement returns True (does "aBBBa" have an "a" at the
'    beginning, an "a" at the end, and any number of characters in 
'    between?)
testCheck = "aBBBa" Like "a*a"
' The following statement returns True (does "F" occur in the set of
'    characters from "A" through "Z"?)
testCheck = "F" Like "[A-Z]"
' The following statement returns False (does "F" NOT occur in the 
'    set of characters from "A" through "Z"?)
testCheck = "F" Like "[!A-Z]"
' The following statement returns True (does "a2a" begin and end with
'    an "a" and have any single-digit number in between?)
testCheck = "a2a" Like "a#a"
' The following statement returns True (does "aM5b" begin with an "a",
'    followed by any character from the set "L" through "P", followed
'    by any single-digit number, and end with any character NOT in
'    the character set "c" through "e"?)
testCheck = "aM5b" Like "a[L-P]#[!c-e]"
' The following statement returns True (does "BAT123khg" begin with a
'    "B", followed by any single character, followed by a "T", and end
'    with zero or more characters of any type?)
testCheck = "BAT123khg" Like "B?T*"
' The following statement returns False (does "CAT123khg"?) begin with
'    a "B", followed by any single character, followed by a "T", and
'    end with zero or more characters of any type?)
testCheck = "CAT123khg" Like "B?T*"

我很确定引擎盖下的LIKE-Operator也是implemented作为RegularExpression的子集,但它更容易用于简单的要求。

以下是LIKE-Operator和RegularExpressions之间的差异列表:

Regular Expressions vs. the Like Operator (Visual Basic)

我喜欢它; - )

答案 1 :(得分:0)