Evan Cathcart
Evan Cathcart

Reputation: 665

How to see if a specific string matches a regex pattern?

I am trying to see if a specific string matches a regex pattern in swift. The code I have so far seems to check if any substring within the given string matches the regex.

let string = " (5"
let pattern = "[0-9]"
if string.rangeOfString(pattern, options: .RegularExpressionSearch) != nil {
        print("matched")
}

The above code returns a match, even though the string as a whole does not match the pattern.

How i would like the code to operate:

" (5" -> no match
"(5"  -> no match
"5"   -> match

How the code currenty operated:

" (5" -> match
"(5"  -> match
"5"   -> match

Upvotes: 4

Views: 4103

Answers (1)

matt
matt

Reputation: 534893

Instead of testing whether the range is nil, look to see whether the range is the whole target string.

let string = "5"
let r = string.characters.indices
let pattern = "[0-9]"
let r2 = string.rangeOfString(pattern, options: .RegularExpressionSearch)
if r2 == r { print("match") }

EDIT Someone asked for a translation into Swift 4:

let string = "5"
let r = string.startIndex..<string.endIndex
let pattern = "[0-9]"
let r2 = string.range(of: pattern, options: .regularExpression)
if r2 == r { print("match") }

Upvotes: 10

Related Questions