Home > other >  swift regex get certaint substrings in string
swift regex get certaint substrings in string

Time:01-31

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

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)!]
    
}

CodePudding user response:

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.

  • Related