How to avoid an error due to special characters in search string when using Regex for a simple search in Swift?

后端 未结 1 1675
不知归路
不知归路 2021-01-22 14:37

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

相关标签:
1条回答
  • 2021-01-22 15:10

    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)"
    
    0 讨论(0)
提交回复
热议问题