Koh
Koh

Reputation: 2897

Swift: Checking Prefix with Regex

I am attempting to check if a string begins with a text that follows a regex pattern. Is there a way to do so using string.hasPrefix()?

My implementation so far:

let pattern = "[Ff][Yy][Ii](.)?"
let regex = try? NSRegularExpression(pattern: pattern, options: [])

if firstRowText.hasPrefix(regex) { //Cannot convert value of type NSRegularExpression to String

}

Upvotes: 2

Views: 1065

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626920

You should use a regex using range(of:options:range:locale:) passing the .regularExpression option with .anchored option:

if firstRowText.range(of: "[Ff][Yy][Ii]", options: [.regularExpression, .anchored]) != nil {...}

The .anchored option makes the regex engine search for a match at the start of the string only.

To make your regex match in a case insensitive way, you may pass another option alongside the current ones, .caseInsensitive, and use a shorter regex, like "FYI":

if firstRowText.range(of: "FYI", options: [.regularExpression, .anchored, .caseInsensitive]) != nil {

See the Swift online demo.

Note that you may also use an inline modifier option (?i) to set case insensitivity:

"(?i)FYI"

Upvotes: 6

Related Questions