Swift中信用卡持卡人姓名验证正则表达式需求及问题
Fixing Your Swift Credit Card Holder Name Validation Regex
Hey there! Let's get that regex sorted out for your credit card holder name checks. I noticed two key issues with your current pattern that are causing apostrophe support to break and even length mismatches—let's break it down step by step.
First, let's recap your requirements to make sure we hit all points:
- Total character length: 2–26
- Allowed characters: Uppercase/lowercase letters, spaces, hyphens (
-), and apostrophes (') - No numbers or other special characters allowed
- Cannot start with a space
The Corrected Regex
Here's the pattern that meets all your needs:
^(?=.{2,26}$)[\p{L}'-][\p{L}\s'-]*$
Let's break down what each part does:
^: Anchors the match to the start of the string(?=.{2,26}$): Positive lookahead to enforce the total length is between 2 and 26 characters (this fixes the length overflow issue in your original regex)[\p{L}'-]: Matches the first character—must be a Unicode letter, apostrophe, or hyphen (so no leading spaces)[\p{L}\s'-]*: Matches all subsequent characters—can be Unicode letters, spaces, apostrophes, or hyphens (the*means zero or more of these)$: Anchors the match to the end of the string
Why Your Original Regex Wasn't Working
- Length mismatch: Your original pattern required 2–26 characters after the first character, making the total length 3–27 (way over your 26-character limit). This could have caused valid names with apostrophes to be rejected if they hit that cap.
- Unintended leading character restriction: Your original
^[^-\\s]excluded hyphens as the first character. Since your requirements don't mention this restriction, our corrected regex fixes that by allowing hyphens/apostrophes as leading characters. If you do want to restrict the first character to only letters, use this variant instead:^(?=.{2,26}$)[\p{L}][\p{L}\s'-]*$
Swift Implementation Example
Here's how you can use this regex in a Swift function for easy validation:
import Foundation func isValidCardHolderName(_ name: String) -> Bool { let regexPattern = "^(?=.{2,26}$)[\\p{L}'-][\\p{L}\\s'-]*$" guard let regex = try? NSRegularExpression(pattern: regexPattern) else { return false } let range = NSRange(location: 0, length: name.utf16.count) return regex.firstMatch(in: name, range: range) != nil } // Test cases print(isValidCardHolderName("Jane O'Neil")) // true print(isValidCardHolderName("Robert-John")) // true print(isValidCardHolderName(" Alice")) // false (leading space) print(isValidCardHolderName("Bob123")) // false (contains number) print(isValidCardHolderName("A")) // false (too short) print(isValidCardHolderName("SuperLongNameThatExceeds26Characters")) // false (too long)
内容的提问来源于stack exchange,提问作者Somya
相关产品推荐
相关产品推荐

