所以,我做了一些研究,但没有提出任何答案。我读到了关于正则表达式的方法,但我在这方面几乎是新的,我从未听说过它。
我尝试做的是确定用户是否输入了密码(在我的情况下我称之为#34;学号和#34;),该密码必须只包含一个大写字母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和字符串末尾的*。
答案 0 :(得分:1)
不需要正则表达式。
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