import Foundation
let pattern = ##"""
(?:(?<=^\n)|(?<=\A)) # Needs 1 or more new lines or start of string
(?<para_all>
(?<para_prefix>[ ]{0,3}) # Possibly some leading spaces, but less than a tab worth
(?<para_content>
(?:
(?! # some line content not starting with those exceptions
[[:blank:]\h]{0,3}
(?:
\*{1}[ \t]+ # a list
|
(?:\*(?:[ ]?\*){2,}) # a horizontal line
|
(?:\-*(?:[ ]?\-){2,}) # a horizontal line
|
(?:\_*(?:[ ]?\_){2,}) # a horizontal line
|
[>+-=\#]
|
\d+\. # ordered list
|
\`{3,} # code block
|
\~{3,} # code block extended
)
)
)
.+
(?!\n(?:[=-]+))
(?:\n|$)
)+
)
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .allowCommentsAndWhitespace])
let testString = ##"""
***This is strong and em.***
The quick brown fox
jumps over the lazy dog
Lorem Ipsum
I should match
- I should NOT match
Le sigh
> Why am I matching?
1. Nonononono!
* Aaaagh!
# Stahhhp!
Hello, World!
==
---
***
***
***
***
***
* * *
* * *
* * *
* * *
___
___
___
___
"""##
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression