Swift 5.0 regularExpression 基本語法範例

let yourStr = "hello"
let result = yourStr.range(of: "he", options: .regularExpression) != nil

結果

true

中文也可以

let yourStr = "史蒂芬賴"
let result = yourStr.range(of: "賴", options: .regularExpression) != nil

[ . ] 任意字串符號(不包含\n)

let yourStr = "史蒂芬賴+1232kdsjsaoj"
let result = yourStr.range(of: ".", options: .regularExpression) != nil

[ \d ] 包含數字

只要有數字就給過

let yourStr = "aaaaaaaaa1"
let result = yourStr.range(of: "\\d", options: .regularExpression) != nil

[ \D ] 包含數字

純數字不給過 其餘混搭過

純數字

let yourStr = "45465464"
let result = yourStr.range(of: "\\D", options: .regularExpression) != nil

結果

false

混搭

let yourStr = "test123"
let result = yourStr.range(of: "\\D", options: .regularExpression) != nil

結果

true

[ \s ] 包含空白

let yourStr = "123 test"
let result = yourStr.range(of: "\\s", options: .regularExpression) != nil

[ \w ] 包含 數字,大小寫英文,底線

let yourStr = "test_Test/"
let result = yourStr.range(of: "\\w", options: .regularExpression) != nil

[ \W ] 不包含 數字,大小寫英文,底線

數字,大小寫英文,底線以外不給過 其餘混搭過

let yourStr = "test_Test/"
let result = yourStr.range(of: "\\w", options: .regularExpression) != nil

符合其中一項

[abd] 有a,b,c其中一個就給過

let yourStr = "123456a"
let result = yourStr.range(of: "abc", options: .regularExpression) != nil

[ + ] 搜尋重複字串

單個 a使用a+
多格 ad使用(ad)+

let yourStr = "adad adadadad"
let result = yourStr.range(of: "(ad)+", options: .regularExpression) != nil
let yourStr = "adad adadadad"
let result = yourStr.range(of: "a+", options: .regularExpression) != nil

待續

"^(?!\\d+)(?![a-zA-Z]+)[0-9A-Za-z]{6,16}"
"^(?=.*\\d)(?=.*[a-zA-Z])[0-9A-Za-z]{6,16}"
Swift更多文章

[教學] Swift 找字串 文字找字串


Swift字串拼接 文字拼接
Swift 字串擷取 文字擷取
Swift – 陣列轉字串 | Array to String | List to String | description
Swift Date 現在星期幾 這個月有幾天
Swift – 正規表達式 (電話/身分證/email)


Categorized in: