Bernd
Bernd

Reputation: 11493

Matching stand-alone substrings in Swift

I want to check if a string is part of another string but only as a standalone term, not as part of another word. I am working in Swift.

E.g. Here's what I would expect checking for "mon"

What's a good way to do this? (going back and forth between NSString functions like containsString and Regular Expressions)

Upvotes: 1

Views: 86

Answers (3)

Mike Chirico
Mike Chirico

Reputation: 3491

The following works with Swift 2.

let regex = try! NSRegularExpression(pattern: "\\bmon\\b", options: NSRegularExpressionOptions.CaseInsensitive)



func isMatch(str: String) -> Bool {
  return regex.firstMatchInString(str, options: .ReportCompletion ,  range: NSRange(location: 0, length: str.characters.count)) != Optional.None
}

["Mon", "mon", " Mon", " Mon " , "Monday", "Hormons"].map(isMatch)

// Yields [true, true, true, true, false, false]

Upvotes: 0

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 59994

let regex = NSRegularExpression(pattern: "\\bmon\\b", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)!

func isMatch(str: String) -> Bool {
    return regex.firstMatchInString(str, options: nil, range: NSRange(location: 0, length: str.utf16Count)) != Optional.None
}

["Mon", "mon", " Mon", " Mon " , "Monday", "Monster", "Hormons"].map(isMatch)

// yields [true, true, true, true, false, false, false]

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Use word boundaries with case insensitive modifier.

"(?i)\\bmon\\b"

DEMO

Upvotes: 3

Related Questions