4

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
Evan Cathcart
  • 635
  • 2
  • 10
  • 13

1 Answers1

10

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") }
matt
  • 515,959
  • 87
  • 875
  • 1,141