Search code examples
swiftregex

Swift Regex not detecting


I have this regex pattern:

let pattern = "\\b(#hashtag)\\b"

It should work for all keywords named: #hashtag, but is doesn’t do that. I have no idea how regexes work so can anyone help me? I am only trying to capture the exact phrase: "#hashtag".


Solution

  • You can use this regex to get the exact match for your string,

    let pattern = "#hashtag\\b"
    

    Here is a sample code you can refer to,

    let pattern = "#hashtag\\b"
    
    validateRegex(inputString: "#hashtag")
    
    func validateRegex(inputString: String) -> Bool {
        
        guard let regularExpression = try? NSRegularExpression(pattern: pattern) else { return false }
        
        let inputValuerange = NSRange(location: 0, length: inputString.count)
        
        return regularExpression.firstMatch(in: inputString, range: inputValuerange) != nil
    }
    

    I have tested it in a playground and it is working fine.

    Regex Matcher Playground