简体   繁体   English

用于密码和电子邮件模式的Visual Basic“赞”运算符

[英]Visual Basic “Like” operator for password and email Pattern

I am trying to use the Like operator to make sure that a String matches against a Pattern. 我正在尝试使用Like运算符来确保String与Pattern匹配。 I know that it is easier to use regex (Regular Expression), but let's just say that I have to use the “like” operator. 我知道使用regex(正则表达式)会更容易,但是我们只能说我必须使用“ like”运算符。 How should I go about it? 我应该怎么做? Any help would be much appreciated. 任何帮助将非常感激。

The password textbox should at least contain one character, one number and one of these symbols #%&*. 密码文本框至少应包含一个字符,一个数字和其中一个符号#%&*。

let's keep it simple and BTW this is how far I've managed to come with the email pattern. 让我们保持简单,顺便说一句,这就是我设法实现的电子邮件模式。

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    If TextBox2.Text Like "*[@]*?.[a-z]*" Then
        MsgBox("OK")
    Else
        MsgBox("NO GOOD")
    End If
End Sub

The password textbox should at least contain one character, one number and one of these symbols #%&*. 密码文本框至少应包含一个字符,一个数字和其中一个符号#%&*。

The only way to solve this with the LIKE operator is to combine multiple LIKE operations, since there's no concept of OR or lookahead/lookbehind like regex. LIKE运算符解决此问题的唯一方法是将多个LIKE运算结合起来,因为没有OR或正则表达式的概念。

Here's an example: 这是一个例子:

Dim strings = {"das6723&", "das6723", "#das6723", 
               "fsdfdfs", "f74/&g3", "232323", 
               "ABC37&28", "J**1", "j87#"}

For Each s in strings
    Console.Write(s)

    If s Like "*#*" AndAlso _ 
       s Like "*[#%&*]*" AndAlso _
       s Like "*[a-zA-Z]*" Then

       Console.WriteLine(" : valid")
    Else
        Console.WriteLine(" : not valid")
    End If
Next

The password textbox should at least contain one character, one number and one of these symbols #%&*. 密码文本框至少应包含一个字符,一个数字和其中一个符号#%&*。

For your requirement you neither need regex nor the Like -operator, this is more efficient and readable as well: 根据您的需求,您既不需要正则表达式也不需要Like -operator,这也更加高效和可读:

Dim isValid = text.Length > 0 AndAlso
    text.Any(AddressOf Char.IsDigit) AndAlso
    text.Any(AddressOf "#%&".Contains)

You should look for regex. 您应该寻找正则表达式。 Here is an example from MSDN for finding email adresses in VB. 这是来自MSDN的示例,用于在VB中查找电子邮件地址。

Function ValidateEmail(ByVal email As String) As Boolean
    Dim emailRegex As New System.Text.RegularExpressions.Regex( 
        "^(?<user>[^@]+)@(?<host>.+)$")
    Dim emailMatch As System.Text.RegularExpressions.Match = 
       emailRegex.Match(email)
    Return emailMatch.Success
End Function

https://msdn.microsoft.com/en-us/library/vstudio/txk0hsah%28v=vs.100%29.aspx https://msdn.microsoft.com/zh-CN/library/vstudio/txk0hsah%28v=vs.100%29.aspx

More on regex in VB: http://support2.microsoft.com/kb/818802 有关VB中正则表达式的更多信息: http : //support2.microsoft.com/kb/818802

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM