繁体   English   中英

如何在VB.net中检查字符串是否包含特定字符?

[英]How can I check if a string contains specific charcaters in VB.net?

因此,我做了一些研究,但没有得出任何答案。 我读过有关Regex方法的信息,但实际上我是新手,但从未听说过。

我要尝试确定的是,用户是否输入了仅包含大写字母S,大写字母S之后的八个数字以及最后一个特殊字符的密码(在我的情况下,我称为“学生编号”) *(具体按该顺序)。

我已经对此进行了编程:

Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click

        Dim InvalidName As Integer = 0
        Dim InvalidStudentNumber_Numeric As Integer = 0

        For intIndex = 0 To txtName.Text.Length - 1
            If IsNumeric(txtName.Text.Substring(intIndex, 1)) Then
                InvalidName = 1
            End If
        Next

        For intIndex = 0 To txtStudentNumber.Text.Length - 1
            If IsNumeric(txtStudentNumber.Text.Substring(intIndex, 1)) Then
                InvalidStudentNumber_Numeric += 1

            End If
        Next

        If InvalidName <> 0 Then
            MessageBox.Show("The name entered does not meet the characters criteria.  Provide a non-numeric name, 10 characters or longer.",
                            "Invalid Information: Name")
            txtName.Focus()

        ElseIf InvalidStudentNumber_Numeric <> 8 Then
            MessageBox.Show("The student number entered does not meet the characters criteria.  Provide a non-numeric student number, 10 characters long.",
                            "Invalid Information: Student Number")
            txtStudentNumber.Focus()

因此,至于学生的名字,我没有问题,但是密码才是我的最爱。 我已经弄清楚了如何知道它是否有数字(必须有8个数字),但是我不知道如何在字符串的开头搜索大写S并在字符串的结尾搜索*。

无需正则表达式。

Public Function IsValidStudentNumber(ByVal id As String) As Boolean
    '  Note that the `S` and the `*` appear to be common to all student numbers, according to your definition, so you could choose to not have the users enter them if you wanted.
    Dim number As Int32 = 0

    id = id.ToUpper

    If id.StartsWith("S") Then
        ' Strip the S, we don't need it.
        ' Or reverse the comparison (not starts with S), if you want to throw an error.
        id = id.Substring(1)
    End If

    If id.EndsWith("*") Then
        ' Strip the *, we don't need it.
        ' Or reverse the comparison (not ends with *), if you want to throw an error.
        id = id.Substring(0, id.Length - 1)
    End If

    If 8 = id.Length Then
        ' Its the right length, now see if its a number.
        If Int32.TryParse(id, number) Then
            Return True
        End If
    End If
    Return False
End Function

暂无
暂无

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

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