Home > Back-end >  Get a part of a string that comes before "_"
Get a part of a string that comes before "_"

Time:10-14

I want to get only the ID that comes before the first "_" but after several attempts I can't do it

String example:

"https://urlexample.com/EXAMPLE_STRING/video/multimedia/20219/27/2022492719125378_1664299242_video_1296.mp4"

The result should be:

"2022492719125378"

Right now I have this but I don't know how to make it only take the first numbers before the first "_"

var str = "https://urlexample.com/EXAMPLE_STRING/video/multimedia/20219/27/2022492719125378_1664299242_video_1296.mp4"

    // file name with extension
    let fileName = string.lastPathComponent
    print(fileName) // "2022092719125378_1664299242_video_1296.mp4" 

    // file id
    let fileId = string.deletingPathExtension.lastPathComponent
    print(fileId) // "2022092719125378_1664299242_video_1296"   

If anyone can help I would appreciate it.

CodePudding user response:

Using components(separatedBy:) or split(separator:). Both works the same if only one character.

let fileId = "2022092719125378_1664299242_video_1296"
let sliptArr = fileId.components(separatedBy: "_")
print(sliptArr[0]) // 2022092719125378
let fileId = "2022092719125378_1664299242_video_1296"
let sliptArr = fileId.split(separator: "_")
print(sliptArr[0]) // 2022092719125378

CodePudding user response:

let str = "https://urlexample.com/EXAMPLE_STRING/video/multimedia/20219/27/2022492719125378_1664299242_video_1296.mp4"

let fieldId = str.components(separatedBy: "/").last?.components(separatedBy: "_").first

print(fieldId)
  • Related