0

I have a string like this:

    let str = "<mylabel>Here is a label</mylabel>"

How can I get a substring with the text "Here is a label" ? Is there any fancy way to do this or do I have to use componentsSeparatedByString? Many thanks

Duarte
  • 127
  • 4
  • 14
  • It looks that you are trying to parse some XML file. Apple has native class for that https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/ – Superian007 Nov 20 '15 at 11:16
  • Thanks for your comment. I was trying to find a "one-liner" solution without going to the full XML stuff. I used XML notation but could be anything else. – Duarte Nov 20 '15 at 11:20

3 Answers3

0

You can use NSAttributedString(HTML:, documentAttributes:) to extract simple HTML entities:

let str = "<mylabel>Here is a label</mylabel>"
if let html = str.dataUsingEncoding(NSUTF8StringEncoding), let result = NSAttributedString(HTML: html, documentAttributes: nil) {
    print(result.string)  // "Here is a label"
}

For more complex work, it would be better to use NSXMLParser or a third-party library.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
0

This sorted the issue:

let str = "<mylabel>Here is a label</mylabel>"
let startIndex = str.rangeOfString("<mylabel>")!.last!
let endIndex = str.rangeOfString("</mylabel>")!.first!
print(str.substringWithRange(Range<String.Index>(start: startIndex.advancedBy(1), end: endIndex)))
Duarte
  • 127
  • 4
  • 14
0

While you generally would not want to use regular expressions to parse XML/HTML, if you know it will have <mylabel> and </mylabel> you can do something like:

let result = str.stringByReplacingOccurrencesOfString("<mylabel>(.*)</mylabel>", withString: "$1", options: .RegularExpressionSearch, range: nil)
Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044