Skip to content

Instantly share code, notes, and snippets.

@davidrhyswhite
Created June 21, 2017 01:03
Show Gist options
  • Save davidrhyswhite/97098803a315a26b0b87ebe497fad3d9 to your computer and use it in GitHub Desktop.
Save davidrhyswhite/97098803a315a26b0b87ebe497fad3d9 to your computer and use it in GitHub Desktop.
Playing with regex in Swift...
extension String {
func capturedGroups(withRegex pattern: String) -> [String] {
var results = [String]()
var regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: pattern, options: [])
} catch {
return results
}
let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.characters.count))
guard let match = matches.first else { return results }
let lastRangeIndex = match.numberOfRanges - 1
guard lastRangeIndex >= 1 else { return results }
for i in 1...lastRangeIndex {
let capturedGroupIndex = match.rangeAt(i)
let matchedString = (self as NSString).substring(with: capturedGroupIndex)
results.append(matchedString)
}
return results
}
}
let string: String = "Lorem ipsum **dolor** sit amet."
let boldGroups = string.capturedGroups(withRegex: "(\\*\\*([\\s\\S]+?)\\*\\*(?!\\*))")
let boldHTML = "<strong>\(boldGroups[1])</strong>"
let htmlBold = string.replacingOccurrences(of: boldGroups[0], with: boldHTML)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment