import Foundation
let pattern = #"(\${1,2})[^]*?[^\\]\1|[^\$]+"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
some text outside $ \$2+\$ $ which includes $\$$
Now some $${}$$ $\{\}$inline mathjax $2+2$
And in new lines
$$
2+2
$$
$
2+2\\
3+3\\
4+4\\
$
more inline $2+2\$ \$2+2$ $2+2$, $3+4$
separated $2+2$ by some text $ 2+2 $ again
double newlines
$2+2$
$2+2$
Dollar again $ \$42 $
$$ \$42 $$
$$
\frac{4}{2}+
\frac{4}{2}
$$
And some more tests:
\> a) $\dr{1}{2}+\left(\dr23-\dr34\right)$<<<
\> b) $\dr{1}{5}+\left(\dr23-\dr12\right)$<<<
\> c) $\dr{1}{2}+\left(\dr{3}{4}-\dr32\right)$<<<
\> d) $\left(\dr{3}{10}-\dr{5}{2}\right)+\dr7{20}$<<<
\> e) $\dr{2}{3}+\left(\dr{3}{2}-\dr14\right)$<<<
\> f) $\left(\dr{14}{5}-\dr7{10}\right)+\dr{11}{10}$.<<<
$$
a^{\rr mn}=\sq[n]{a^m}.
$$
$$
\begin{align}
&a^x\cdot a^y=a^{x+y}\\
&\dr{a^x}{a^y}=a^{x-y}\\
&(a^x)^y=a^{xy}\\
&(ab)^x=a^xb^x\\
&\left(\dr ab\right)^x=\dr{a^x}{b^x}.
\end{align}
$$
$$
\sq[4]{5\sq5}=(5\sq5)^{\rr14}=(5\.5^{\rr12})^{\rr14}=
(5^{1+\rr12})^{\rr14}=(5^{\rr32})^{\rr14}=5^{\rr38}.
$$
Hope that's it.
"""#
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