[英]How can I check if a string contains specific charcaters in VB.net?
So, I did some research but didn't come up with any answers. 因此,我做了一些研究,但没有得出任何答案。 I read about the Regex method, but I'm practically new in this and I have never heard of it. 我读过有关Regex方法的信息,但实际上我是新手,但从未听说过。
What I'm trying to do is to identify, whether the user entered a password (in my case I call it "Student Number") that must only contain an uppercase letter S, eight numbers after the uppercase S, and finally a special character * (specifically in that order). 我要尝试确定的是,用户是否输入了仅包含大写字母S,大写字母S之后的八个数字以及最后一个特殊字符的密码(在我的情况下,我称为“学生编号”) *(具体按该顺序)。
I already programmed this: 我已经对此进行了编程:
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()
So, as for the Student's Name I have no problems, but the password is what gets me. 因此,至于学生的名字,我没有问题,但是密码才是我的最爱。 I already figured out how to know if it has numbers (it must have 8), but I don't know how to search for the uppercase S at the beginning and for the * at the end of the string. 我已经弄清楚了如何知道它是否有数字(必须有8个数字),但是我不知道如何在字符串的开头搜索大写S并在字符串的结尾搜索*。
No need for regex. 无需正则表达式。
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.