2016-06-15 7 views
-1

私はユーザー名正規表現で、a-z、A-Z、0-9、および_の文字のみを受け付けています。現在のユーザー名の最大長は18文字で、最低1文字です。私の現在の正規表現は以下の通りです。SwiftのRegexの問題

せregexCorrectPattern = "[-ZA-Z0-9 _] {1,18} $"

私は次の問題が生じています。文字列の末尾以外に特殊文字を追加すると、正規表現を渡すことができます。例えば、

jon!

をFAIL!JON PASS

J!PASS

に、私は正規表現をテストするために使用していますメソッドは、呼び出し元のメソッドと一緒に以下の通りです。どんな入力も非常に高く評価されます。

正規表現試験方法が

func regexTestString(string: String, withPattern regexPattern: String) -> Bool 
{ 
     // This method is used for all of the methods below. 
     do 
     { 
      // Create regex and regex range. 
      let regex = try NSRegularExpression(pattern: regexPattern, options: .CaseInsensitive) 
      let range = NSMakeRange(0, string.characters.count) 

      // Test for the number of regex matches. 
      let numberOfMatches = regex.numberOfMatchesInString(string, options: [], range: range) 

      // Testing Code. 
      print(numberOfMatches) 

      // Return true if the number of matches is greater than 1 and return false if the number of mathces is 0. 
      return (numberOfMatches == 0) ? false : true 
     } 
     catch 
     { 
      // Testing Code 
      print("There is an error in the SignUpViewController regexTestString() method \(error)") 

      // If there is an error return false. 
      return false 
     } 
    } 

あなたが指定した文字のみを格納するための文字列全体をしたい方法

func usernameTextFieldDidEndEditing(sender: AnyObject) 
    { 
     let usernameText = self.usernameField.text!.lowercaseString 

     let regexCorrectPattern = "[a-zA-Z0-9_]{1,18}$" 
     let regexWhitespacePattern = "\\s" 
     let regexSpecialCharacterPattern = ".*[^A-Za-z0-9].*" 

     if regexTestString(usernameText, withPattern: regexCorrectPattern) 
     { 
      // The regex has passed hide the regexNotificationView 

     } 
     else if regexTestString(usernameText, withPattern: regexWhitespacePattern) 
     { 
      // The username contains whitespace characters. Alert the user. 
     } 
     else if regexTestString(usernameText, withPattern: regexSpecialCharacterPattern) 
     { 
      // The username contains special characters. Alert the user. 
     } 
     else if usernameText == "" 
     { 
      // The usernameField is empty. Make sure the sign up button is disabled. 
     } 
     else 
     { 
      // For some reason the Regex is false. Disable the sign up button. 
     } 
    } 
+0

'az、A -Z、0-9、_' '' jon'はどうやって渡すべきですか? –

答えて

1

を呼び出すので、あなたが必要とするすべては、パターンの開始時に^を追加することです:

^[a-zA-Z0-9_]{1,18}$

+0

恐ろしい!それは完璧に働いた。助けてくれてありがとう。 – jonthornham