read
In the latest Swift, you can create a Regex (iOS 16+) using slash syntax such as /(\d+)/
(to capture 1 or more digits).
You can then access the match using the new firstMatch(of:)
.
let regex = /(\d+)/
if let match = someString.firstMatch(of: regex) {
print("1st captured group of digits: \(match.1)")
}
Compile error with slash
But you might run into the following error, especially for Swift packages:
’/’ is not a prefix unary operator.
This is because the literal syntax is disabled since it is a breaking change.
The workaround is to enable the flag:
// swift-tools-version: 5.7
import PackageDescription
let package = Package(...)
for target in package.targets {
target.swiftSettings = target.swiftSettings ?? []
target.swiftSettings?.append(
.unsafeFlags([
"-enable-bare-slash-regex",
])
)
}
Alternatively, you can use without the literal syntax support by using Regex
string initializer.