Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 240
Evan Cathcart Avatar asked Dec 24 '22 08:12

Evan Cathcart


1 Answers

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") }
like image 190
matt Avatar answered Jan 07 '23 17:01

matt