问题描述
我正在尝试创建一个方法,用于查找字符串是否包含数字,大写字母和使用正则表达式的特殊字符,如下所示
I am trying to create a method that finds whether a string contains a number , Upper case letter and a special character using regular expression as below
func checkTextSufficientComplexity(var text : String) -> Bool{
let capitalLetterRegEx = "[A-Z]+"
var texttest = NSPredicate(format:"SELF MATCHES %@", capitalLetterRegEx)
var capitalresult = texttest.evaluateWithObject("AniP")
println("\(capitalresult)")
let numberRegEx = "[0-9]+"
var texttest1 = NSPredicate(format:"SELF MATCHES %@", numberRegEx)
var numberresult = texttest1.evaluateWithObject(text)
println("\(numberresult)")
let specialCharacterRegEx = "[.*&^%$#@()/]+"
var texttest2 = NSPredicate(format:"SELF MATCHES %@", numberRegEx)
var specialresult = texttest2.evaluateWithObject(text)
println("\(specialresult)")
return capitalresult && numberresult && specialresult
}
问题是以下正则表达式[AZ] +仅返回例如AVATAR的true,并为Avatar返回false。我希望我的正则表达式返回true,如果它在String中包含至少一个UpperCase。
The problem is the below regular expression [A-Z]+ returns true for only e.g AVATAR and returns false for Avatar. I want my regular expression return true if it contains at least one UpperCase in String.
推荐答案
只需替换您的RegEx规则[AZ] + with。* [AZ] +。*(以及其他RegEx规则)
Simply replace your RegEx rule [A-Z]+ with .*[A-Z]+.* (and other RegEx rules as well)
规则
示例:AVATAR,AVA,TAR,AAAAAA
无效:AVATAr
示例:1,2,AVATAR,AVA ,TAR,a,b,c
示例:Avatar,avataR,aVatar
说明:
我。 。*将尝试匹配0或更多的任何东西
II。 [A-Z] +将需要至少一个大写字母(因为+)
III。 。*将尝试匹配0或更多的任何东西
I. .* will try to match 0 or more of anything
II. [A-Z]+ will require at least one capital letter (because of the +)
III. .* will try to match 0 or more of anything
工作代码
func checkTextSufficientComplexity(var text : String) -> Bool{
let capitalLetterRegEx = ".*[A-Z]+.*"
var texttest = NSPredicate(format:"SELF MATCHES %@", capitalLetterRegEx)
var capitalresult = texttest!.evaluateWithObject(text)
println("\(capitalresult)")
let numberRegEx = ".*[0-9]+.*"
var texttest1 = NSPredicate(format:"SELF MATCHES %@", numberRegEx)
var numberresult = texttest1!.evaluateWithObject(text)
println("\(numberresult)")
let specialCharacterRegEx = ".*[!&^%$#@()/]+.*"
var texttest2 = NSPredicate(format:"SELF MATCHES %@", specialCharacterRegEx)
var specialresult = texttest2!.evaluateWithObject(text)
println("\(specialresult)")
return capitalresult || numberresult || specialresult
}
示例:
checkTextSufficientComplexity("Avatar") // true || false || false
checkTextSufficientComplexity("avatar") // false || false || false
checkTextSufficientComplexity("avatar1") // false || true || false
checkTextSufficientComplexity("avatar!") // false || false || true
这篇关于检查字符串是否至少包含swift中的upperCase字母,数字或特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!