0

I'm not looking for how to find a string inside another string. I'm looking for a word. So the solution should pass these tests:

let result: Bool = senx.contains(word: "are")

let sen1 = "We are good." //true
let sen2 = "We care about you." //false
let sen3 = "are"  //true
let sen4 = "are."  //true
let sen5 = "Are."  //true
let sen6 = "I have a flare." //false
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168

1 Answers1

4

You need a regex with a word boundaries \b around the value you are checking the presence for:

let pattern = "(?i)\\bare\\b"
if string.rangeOfString(pattern, options: .RegularExpressionSearch) != nil ...

The \bare\b matches any are that is a whole word (not preceded nor followed with letters/digits/underscores. The (?i) flag ensures a case insensitive search. See the regex demo.

See this SO answer for the code to check if a pattern matches a string.

See regular-expressions.info Word boundaries for more information on what \b word boundary does.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Just FYI: If you only want to match `Are` or `are` as whole words, but you do not want to detect `ARe` or `ARE` or `aRe`, etc. use *alternation*: `let pattern = "\\b(?:are|Are)\\b"` – Wiktor Stribiżew Sep 28 '16 at 13:24