我正在使用用戶名正則表達式,其中唯一接受的字符是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.
}
}
'AZ,A -Z,0-9,和''jon'應該怎麼通過? –