Swift 3 line contains exact sentence / word

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

I'm not looking for:

string.contains(anotherString)

That's why:

let string = "I know your name"
string.contains("you") // Will return true

In the above example, it returns true, because if find is "you"in the word "your". I want a method that will return false in this state.

For instance:

let string = "I am learning Swift"

// Let say we make a method using extension called contains(exact:)
string.contains(exact: "learn") // return false

The method contains(exact:)will return false, since it is "learn"not equal"learning"

Another example:

let string = "Healthy low carb diets"
string.contains(exact: "low carb diet") // return false

What algorithm will get this result in Swift 3? Or is there a predefined method for this?

+6
source share
3 answers

The solution is a regular expression that can check word boundaries.

String, , (\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
        }
    }
}

- -

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

:

let string = "I know your name"
string.contains(word:"your") // true
string.contains(word:"you") // false
+10

:

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)

.

+2
func containsExact(_ findString: String, _ inString: String) -> Bool {
    let expression = "\\b\(findString)\\b"
    return inString.range(of: expression, options: .regularExpression) != nil
}
0
source

Source: https://habr.com/ru/post/1682751/


All Articles