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
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
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.
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)))
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)