Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

swift regex get certaint substrings in string

I have a string like this one and i want to get the text after src= to the end of .m3u8.

Example:

let string = "loremipsum-src=https://loremipsum.m3u8&pano-src=https://loremimpum.m3u8&proj"

I want to get the substrings https://loremipsum.m3u8

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what I am trying for now:

let regex = try! NSRegularExpression(pattern: "src=(.*?).m3u8", options: .caseInsensitive)
if let match = regex.firstMatch(in: string, range: NSRange(NSRange(string.index(string.startIndex, offsetBy: 4)..., in: string)) {
    
    let substring = string[Range(match.range(at: 1), in: string)!]
    
}

>Solution :

let string = "loremipsum-src=https://loremipsum.m3u8&pano-src=https://loremimpum.m3u8&proj"

let regex = try! NSRegularExpression(pattern: "src=(https://.*?.m3u8)", options: .caseInsensitive)
if let match = regex.firstMatch(in: string, range: NSRange(string.startIndex..., in: string)) {
  let range = match.range(at: 1)
  let output = (string as NSString).substring(with: range)
  print(output) // // https://loremipsum.m3u8
}

ps – if u user your pattern as "src=(.*?.m3u8)"(changed the bracket) it will also work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading