-2

I am new to Swift and I want to make some regex to check if a string matches with a certain pattern.

I have this URL:

http://server.com/folder/image_09.jpg

URL can also be:

http://server.com/folder/image.jpg

And I want to check if the string matches this pattern:

sometext + _two characters + .jpg
Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72

1 Answers1

1

Your search pattern could be "_\w{2}\.jpg$"

let regExp = NSRegularExpression(pattern: "_\\w{2}\\.jpg$", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)
let urlString = "http://www.foo.it/image_00.jpg"
let range = NSRange(location: 0, length: count(urlString.utf16))
if let numberMatches = regExp?.numberOfMatchesInString(urlString, options: NSMatchingOptions(0), range: range)
    where numberMatches == 1 {
        let s = "OK"
} else {
    let s = "No matches found"
}

Hope this helps

Matteo Piombo
  • 6,688
  • 2
  • 25
  • 25
  • `count(urlString.utf8)` should be `(urlString as NSString).length` or `count(urlString.utf16)`, otherwise it crashes for strings containing non-ASCII characters, e.g. `urlString = "http://www.foo.it/äöüimage_00.jpg"` . Compare http://stackoverflow.com/a/27880748/1187415. – Martin R Jun 04 '15 at 22:20
  • @MartinR Edited. Didn't think about it since commonly urls comes from utf8 encoded pages. Thanks – Matteo Piombo Jun 04 '15 at 23:19