2015-10-15 132 views
0

有一些方法可以防止用户只允许字母,数字和单个空格。说字母我认为只有字母(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

您面临什么错误? – prasun

+0

我没有面对任何错误 - 我只想扩展提到的代码,以不允许用户也把字符,如:ę,Ę,ąĄ,śŚ,żŻ等。 – Arie

+0

问题是检查'IsLetterOrDigit'函数不需要使用** Not **关键字,您应该尝试'Char.IsLetterOrDigit(c)'而不是'Not Char.IsLetterOrDigit(c)'。像这样 - http://hastebin.com/ohodanipef.vbs –

回答

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")) 
+0

我问不使用正则表达式,但扩展了我提到的。 – Arie

+0

无论如何,根据你的例子是否只允许使用a-z,A-Z,数字, - ,单个空格是否真的不允许任何其他字符?如果是这样如何取代我的现有循环由我,我从来没有使用正则表达式 – Arie

+1

@StackUser: - 更新我的答案。 –

相关问题