-2

I have strings in form of an URL. The strings looks like

http://www.somezwebsite.com/en/someString/xx-38944672

I am interested on the last part of the URL, the /xx-38944672. I need to extract the xx between the last / and the - which could be one or more characters. I also need to extract the number, 38944672 in this example. The number could also have a different length.

I think I could achieve this by determining the index of the last / the index of the last - and the index of the last character in the string, then proceed the sub-strings. Is there a cleaner way to do this?

J.Doe
  • 697
  • 2
  • 16
  • 26
  • split using '/' and then in the last element of the array (xx-38944672) split again and use '-' as the separator, your xx will be the first element of the array now, more info in: https://stackoverflow.com/questions/25678373/swift-split-a-string-into-an-array – João Silva May 24 '17 at 10:17
  • Anyway the regex is `/([^/]+?)-(\d+)` – logi-kal May 24 '17 at 10:22

3 Answers3

1

This is the one you needed:

/\w+(?=-)/g

DEMO

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
0

The keyword URL implies a part of the solution

The code takes the last path component of the URL and separates the value into two parts by the - character:

let url = URL(string:"http://www.somezwebsite.com/en/someString/xx-38944672")!
let components = url.lastPathComponent.components(separatedBy: "-")
if components.count == 2 {
    let firstPart = components[0]
    let secondPart = components[1]
    print(firstPart, secondPart)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0

It can be done this way:

let urlString = "http://www.somezwebsite.com/en/someString/xx-38944672"
        let str = urlString.components(separatedBy: "/").last
        let firstSring = str?.components(separatedBy: "-").first
        let secondString = str?.components(separatedBy: "-").last
Vamshi Krishna
  • 979
  • 9
  • 19