You can use a simple regular expression for this.
The .*
parameter is hungry and will try to match as much as possible of the url subject:message pair before the (hopefully) last @ character in the string.
I have also included a small tool function (rangeFromNSRange()
) to help convert an Objective-C NSRange
struct into a proper Range<String.Index>
Swift struct.
Paste the following in a Swift playground to see it working (and have fun!):
import Cocoa
func rangeFromNSRange(range: NSRange, string: String) -> Range<String.Index>
{
let startIndex = string.startIndex.advancedBy(range.location)
let endIndex = startIndex.advancedBy(range.length)
return Range(start: startIndex, end: endIndex)
}
func parseEmailURL(urlAsString url: String) -> (subject: String, message: String)?
{
let regexFormat = "^(.*):(.*)@"
if let regex = try? NSRegularExpression(pattern: regexFormat, options: NSRegularExpressionOptions.CaseInsensitive)
{
let matches = regex.matchesInString(url, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, url.characters.count))
if let match = matches.first
{
let subjectRange = rangeFromNSRange(match.rangeAtIndex(1), string: url)
let messageRange = rangeFromNSRange(match.rangeAtIndex(2), string: url)
let subject = url.substringWithRange(subjectRange)
let message = url.substringWithRange(messageRange)
return (subject, message)
}
}
return nil
}
parseEmailURL(urlAsString: "message:2004768713.4671@mail.stackoverflow.com")