2016-06-15 46 views
-1

我正在使用用戶名正則表達式,其中唯一接受的字符是a-z,A-Z,0-9和_。用戶名的當前最大長度爲18個字符,最少爲1個。我目前的正則表達式在下面。Swift中的正則表達式

讓regexCorrectPattern = 「[A-ZA-Z0-9 _] {1,18} $」

我有以下問題。在字符串末尾添加的特殊字符允許正則表達式通過。例如

jon! FAIL

!喬恩PASS

J 1對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

相關問題