Bartłomiej Semańczyk Bartłomiej Semańczyk - 4 years ago 175
Swift Question

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

I have a following


to find them in text I have created following regular expression:

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

But within the following text:

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

only the first one is found. How to change the regex to find every of them?

Answer Source

You can use 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.

Sample usage for your scenario:

let userName = NSRegularExpression.escapedPatternForString("iphone6+_taylor")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download