Swift 3 String Contains Exact Sentence / Word

前端 未结 3 1346
梦谈多话
梦谈多话 2020-12-19 09:03

I would like to know a simple algorithm to determine if a string contains exact sentence or word.

I\'m not looking for:

string.contain

相关标签:
3条回答
  • 2020-12-19 09:12

    A solution is Regular Expression which is able to check for word boundaries.

    This is a simple String extension, the pattern searches for the query string wrapped in word boundaries (\b)

    extension String {
        func contains(word : String) -> Bool
        {
            do {
                let regex = try NSRegularExpression(pattern: "\\b\(word)\\b")
                return regex.numberOfMatches(in: self, range: NSRange(word.startIndex..., in: word)) > 0
            } catch {
                return false
            }
        }
    }
    

    Or – thanks to Sulthan – still simpler

    extension String {
        func contains(word : String) -> Bool
        {
            return self.range(of: "\\b\(word)\\b", options: .regularExpression) != nil
        }
    }
    

    Usage:

    let string = "I know your name"
    string.contains(word:"your") // true
    string.contains(word:"you") // false
    
    0 讨论(0)
  • 2020-12-19 09:18

    A regexless solution would be something like:

    yourString.components(separatedBy: CharacterSet.alphanumerics.inverted)
        .filter { $0 != "" } // this is here os that it always evaluates to false if wordToFind is "". Feel free to remove this line if you don't need it.
        .contains(wordToFind)
    

    This will treat every non-alphanumeric character as a word boundary.

    0 讨论(0)
  • 2020-12-19 09:22
    func containsExact(_ findString: String, _ inString: String) -> Bool {
        let expression = "\\b\(findString)\\b"
        return inString.range(of: expression, options: .regularExpression) != nil
    }
    
    0 讨论(0)
提交回复
热议问题