如何排除“+”在 NSRegularExpression 中被视为特殊字符?

How to exclude "+" from being treated as special character in NSRegularExpression?

我有以下 userNameiphone6s_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")