ios - 如何排除 "+"在 NSRegularExpression 中被视为特殊字符?

标签 ios regex swift nsregularexpression

我有以下用户名:iphone6s_tayloriphone6+_taylor

为了在我创建的以下正则表达式的文本中找到它们:

let regex = "\\B@\(userName)\\b"

但在以下文本中:

let text = "@iphone6s_taylor @iphone6+_taylor @iphone6+_taylor"

仅找到第一个。如何更改正则表达式来找到它们中的每一个?

最佳答案

您可以使用escapedPatternForString :

Returns a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as pattern metacharacters.

您的场景的示例用法:

let userName = NSRegularExpression.escapedPatternForString("iphone6+_taylor")

关于ios - 如何排除 "+"在 NSRegularExpression 中被视为特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34652174/

相关文章:

iphone - 未调用 willSendRequestForAuthenticationChallenge

javascript - 如何使用 RegEx 检查表单输入是否以 .pdf 结尾

ios - CallKit com.apple.CallKit.error.calldirectorymanager 错误 1

swift - RxSwift + RxRealm + RxCocoa 向 UITableView 插入行

ios - 如何使 UIViews 以淡入方式过渡到可见状态?

ios - 运行 Storyboard 项目时,符合 Monotouch 键值编码标准的崩溃

ios - NSArray 元素无法匹配 Swift 数组元素类型的原因

regex - 查找/替换 : regex with some logic, 引号——从输入文件到输出文件,单遍

Python:使用正则表达式捕获模式中的子模式

ios - 80 年代的 4 月 1 日日期在 iOS 10.0 中无法解析