有一些方法可以保护用户只允许字母,数字,和单个空格。说字母我认为只有字母(a-z和A-Z),但没有例如,,Ę,±Ą,śŚ,żŻ等...你能帮我修理下面的代码来检查那个吗? (不使用正则表达式)
For Each c As Char In txtSymbol.Text
If Not Char.IsLetterOrDigit(c) AndAlso c <> "-"c AndAlso c <> " " Then
MessageBox.Show("Only lower/upper letters, digits, - and single spaces are allowed"", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Exit Try
End If
Next
有待进一步讨论:
'--We elping user with leading and ending spaces to be removed and more than one space in same placed to be convert to only one space
Dim str As String = txtNazwa.Text.Trim 'deleting leading and ending spaces
While str.Contains(" ") 'deleting more than one space in same place
str = str.Replace(" ", " ")
End While
txtNazwa.Text = str 'corrected one we passed to textbox
'Now we checking further for only those can be presented to pass test:
'--> single space
'--> letters a-z A-Z
'--> digits
'--> -
Dim pattern As String = "^([a-zA-Z0-9-]+\s)*[a-zA-Z0-9-]+$"
Dim r As New Regex(pattern)
If Not r.IsMatch(str) Then
Exit Try
End If
答案 0 :(得分:1)
您可以尝试使用此正则表达式:
^([a-zA-Z0-9-]+\s)*[a-zA-Z0-9-]+$
<强> Regex Demo 强>
在您的代码中,您可以这样尝试:
Dim str As String = "^[a-zA-Z0-9 ]*$"
Dim r As New Regex(str)
Console.WriteLine(r.IsMatch("yourInputString"))