I\'m using Regex to search for a word in a textView. I implemented a textField and two switch as options (Whole words and Match case). All work fine when you enter a plain word
You may use NSRegularExpression.escapedPatternForString:
Returns a string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters.
Thus, you need
var pattern = NSRegularExpression.escapedPatternForString(searchString)
Also, note that this piece:
if isWholeWords {
pattern = "\\b\(searchString)\\b"
might fail if a user inputs (text)
and wishes to search for it as a whole word. The best way to match whole words is by means of lookarounds disallowing word chars on both ends of the search word:
if isWholeWords {
pattern = "(?<!\\w)" + NSRegularExpression.escapedPatternForString(searchString) + "(?!\\w)"