Bas*_*sil 1 string swift swift4 ios11
我尝试将'符号包含在正则表达式中
我用这个功能
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
text.substring(with: Range($0.range, in: text)!)
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
Run Code Online (Sandbox Code Playgroud)
和这个正则表达式
let matched = matches(for: "^[‘]|[0-9]|[a-zA-Z]+$", in: string)
Run Code Online (Sandbox Code Playgroud)
当我搜索时,我可以找到数字和英文字母
但不是'符号
我猜你真正想要的是这个:
"['0-9a-zA-Z]+"
Run Code Online (Sandbox Code Playgroud)
请注意,我已删除^(文本开头)和$(文本结束)字符,因为这样您的整个文本必须匹配.
我合并了这些组,因为否则你不会将文本作为整个单词进行匹配.你会得到单独的撇号,然后是单词.
我把‘角色改成了正确的'角色.简单撇号的自动转换是由iOS 11 Smart Punctuation引起的.您可以使用以下命令将其关闭:
input.smartQuotesType = .no
Run Code Online (Sandbox Code Playgroud)
请参阅https://developer.apple.com/documentation/uikit/uitextinputtraits/2865931-smartquotestype
| 归档时间: |
|
| 查看次数: |
917 次 |
| 最近记录: |