Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift regex for checking if string has at least one uppercase letter

I have tried several things like:

^(?=.*?[A-Z])
^(?=.*?[A-Z])$
^(.*?[A-Z])$

nothing works

static func atLeastOneUpperCase(_ input: String) -> Bool {
    return NSPredicate(format: "SELF MATCHES %@", upperCaseRegex).evaluate(with: input)
}

The input should be one of the above.

like image 380
user3239711 Avatar asked Oct 21 '25 15:10

user3239711


2 Answers

In Swift, when you use NSPredicate with MATCHES, you require a full string match.

So, in your case, you need to use

let upperCaseRegex = "(?s)[^A-Z]*[A-Z].*"

This will match a whole string that starts with 0+ chars other than uppercase ASCII letters, then will match 1 ASCII letter, and then will match any 0+ chars (since (?s) allows a dot to match any char including line break characters).

Another way is to use range(of:options:range:locale:), passing the .regularExpression option:

return input.range(of: "[A-Z]", options: .regularExpression) != nil

This will allow matching a regex in an unanchored way, i.e. this way, the regex engine will be looking for a partial match, and won't require the full string match any longer.

Unicode considerations

If you need to check for any Unicode uppercase letter, use \p{Lu} instead of [A-Z]:

return input.range(of: "\\p{Lu}", options: .regularExpression) != nil

Or, if you need to use NSPredicate version:

let upperCaseRegex = "(?s)\\P{Lu}*\\p{Lu}.*"

Note that here, \P{Lu}* matches 0+ chars other than uppercase letters.

like image 196
Wiktor Stribiżew Avatar answered Oct 23 '25 04:10

Wiktor Stribiżew


If you aren't checking for any particular position of the capital letter then [A-Z] will work. For example in javascript I would use /[A-Z]/.test("fRed") and get true and /[A-Z]/.test("fred") returns false.

like image 36
scrappedcola Avatar answered Oct 23 '25 04:10

scrappedcola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!