1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@available(SwiftStdlib 5.7, *)
extension Regex {
/// The result of matching a regular expression against a string.
///
/// A `Match` forwards API to the `Output` generic parameter,
/// providing direct access to captures.
@dynamicMemberLookup
public struct Match {
let anyRegexOutput: AnyRegexOutput
/// The range of the overall match.
public let range: Range<String.Index>
}
}
@available(SwiftStdlib 5.7, *)
extension Regex.Match {
var input: String {
anyRegexOutput.input
}
/// The output produced from the match operation.
public var output: Output {
if Output.self == AnyRegexOutput.self {
return anyRegexOutput as! Output
}
let typeErasedMatch = anyRegexOutput.existentialOutput(
from: anyRegexOutput.input
)
return typeErasedMatch as! Output
}
/// Accesses a capture by its name or number.
public subscript<T>(dynamicMember keyPath: KeyPath<Output, T>) -> T {
// Note: We should be able to get the element offset from the key path
// itself even at compile time. We need a better way of doing this.
guard let outputTupleOffset = MemoryLayout.tupleElementIndex(
of: keyPath, elementTypes: anyRegexOutput.map(\.type)
) else {
return output[keyPath: keyPath]
}
return anyRegexOutput[outputTupleOffset].value as! T
}
/// Accesses a capture using the `.0` syntax, even when the match isn't a tuple.
@_disfavoredOverload
public subscript(
dynamicMember _keyPath: KeyPath<(Output, _doNotUse: ()), Output>
) -> Output {
output
}
// Helper for `subscript(_: Reference<Capture>)`, defined in RegexBuilder.
@_spi(RegexBuilder)
public subscript<Capture>(_ id: ReferenceID) -> Capture {
guard let element = anyRegexOutput.first(
where: { $0.representation.referenceID == id }
) else {
preconditionFailure("Reference did not capture any match in the regex")
}
return element.existentialOutputComponent(
from: input
) as! Capture
}
}
@available(SwiftStdlib 5.7, *)
extension Regex {
/// Returns a match if this regex matches the given string in its entirety.
///
/// Call this method if you want the regular expression to succeed only when
/// it matches the entire string you pass as `string`. The following example
/// shows matching a regular expression that only matches digits, with
/// different candidate strings.
///
/// let digits = /[0-9]+/
///
/// if let digitsMatch = try digits.wholeMatch(in: "2022") {
/// print(digitsMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "2022"
///
/// if let digitsMatch = try digits.wholeMatch(in: "The year is 2022.") {
/// print(digitsMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "No match."
///
/// The `wholeMatch(in:)` method can throw an error if this regex includes
/// a transformation closure that throws an error.
///
/// - Parameter string: The string to match this regular expression against.
/// - Returns: The match, if this regex matches the entirety of `string`;
/// otherwise, `nil`.
public func wholeMatch(in string: String) throws -> Regex<Output>.Match? {
try _match(string, in: string.startIndex..<string.endIndex, mode: .wholeString)
}
/// Returns a match if this regex matches the given string at its start.
///
/// Call this method if you want the regular expression to succeed only when
/// it matches only at the start of the given string. This example uses
/// `prefixMatch(in:)` and a regex that matches a title-case word to search
/// for such a word at the start of different strings:
///
/// let titleCaseWord = /[A-Z][A-Za-z]+/
///
/// if let wordMatch = try titleCaseWord.prefixMatch(in: "Searching in a Regex") {
/// print(wordMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "Searching"
///
/// if let wordMatch = try titleCaseWord.prefixMatch(in: "title case word at the End") {
/// print(wordMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "No match."
///
/// The `prefixMatch(in:)` method can throw an error if this regex includes
/// a transformation closure that throws an error.
///
/// - Parameter string: The string to match this regular expression against.
/// - Returns: The match, if this regex matches at the start of `string`;
/// otherwise, `nil`.
public func prefixMatch(in string: String) throws -> Regex<Output>.Match? {
try _match(string, in: string.startIndex..<string.endIndex, mode: .partialFromFront)
}
/// Returns the first match for this regex found in the given string.
///
/// Use the `firstMatch(in:)` method to search for the first occurrence of
/// this regular expression in `string`. This example searches for the first
/// sequence of digits that occurs in a string:
///
/// let digits = /[0-9]+/
///
/// if let digitsMatch = try digits.firstMatch(in: "The year is 2022; last year was 2021.") {
/// print(digitsMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "2022"
///
/// The `firstMatch(in:)` method can throw an error if this regex includes
/// a transformation closure that throws an error.
///
/// - Parameter string: The string to match this regular expression against.
/// - Returns: The match, if one is found; otherwise, `nil`.
public func firstMatch(in string: String) throws -> Regex<Output>.Match? {
try _firstMatch(string, in: string.startIndex..<string.endIndex)
}
/// Returns a match if this regex matches the given substring in its entirety.
///
/// Call this method if you want the regular expression to succeed only when
/// it matches the entire string you pass as `string`. The following example
/// shows matching a regular expression that only matches digits, with
/// different candidate strings.
///
/// let digits = /[0-9]+/
///
/// if let digitsMatch = try digits.wholeMatch(in: "2022") {
/// print(digitsMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "2022"
///
/// if let digitsMatch = try digits.wholeMatch(in: "The year is 2022.") {
/// print(digitsMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "No match."
///
/// The `wholeMatch(in:)` method can throw an error if this regex includes
/// a transformation closure that throws an error.
///
/// - Parameter string: The substring to match this regular expression
/// against.
/// - Returns: The match, if this regex matches the entirety of `string`;
/// otherwise, `nil`.
public func wholeMatch(in string: Substring) throws -> Regex<Output>.Match? {
try _match(string.base, in: string.startIndex..<string.endIndex, mode: .wholeString)
}
/// Returns a match if this regex matches the given substring at its start.
///
/// Call this method if you want the regular expression to succeed only when
/// it matches only at the start of the given string. This example uses
/// `prefixMatch(in:)` and a regex that matches a title-case word to search
/// for such a word at the start of different strings:
///
/// let titleCaseWord = /[A-Z][A-Za-z]+/
///
/// if let wordMatch = try titleCaseWord.prefixMatch(in: "Searching in a Regex") {
/// print(wordMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "Searching"
///
/// if let wordMatch = try titleCaseWord.prefixMatch(in: "title case word at the End") {
/// print(wordMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "No match."
///
/// The `prefixMatch(in:)` method can throw an error if this regex includes
/// a transformation closure that throws an error.
///
/// - Parameter string: The substring to match this regular expression
/// against.
/// - Returns: The match, if this regex matches at the start of `string`;
/// otherwise, `nil`.
public func prefixMatch(in string: Substring) throws -> Regex<Output>.Match? {
try _match(string.base, in: string.startIndex..<string.endIndex, mode: .partialFromFront)
}
/// Returns the first match for this regex found in the given substring.
///
/// Use the `firstMatch(in:)` method to search for the first occurrence of
/// this regular expression in `string`. This example searches for the first
/// sequence of digits that occurs in a string:
///
/// let digits = /[0-9]+/
///
/// if let digitsMatch = try digits.firstMatch(in: "The year is 2022; last year was 2021.") {
/// print(digitsMatch.0)
/// } else {
/// print("No match.")
/// }
/// // Prints "2022"
///
/// The `firstMatch(in:)` method can throw an error if this regex includes
/// a transformation closure that throws an error.
///
/// - Parameter string: The substring to match this regular expression
/// against.
/// - Returns: The match, if one is found; otherwise, `nil`.
public func firstMatch(in string: Substring) throws -> Regex<Output>.Match? {
try _firstMatch(string.base, in: string.startIndex..<string.endIndex)
}
func _match(
_ input: String,
in subjectBounds: Range<String.Index>,
mode: MatchMode = .wholeString
) throws -> Regex<Output>.Match? {
let executor = Executor(program: regex.program.loweredProgram)
return try executor.match(input, in: subjectBounds, mode)
}
func _firstMatch(
_ input: String,
in subjectBounds: Range<String.Index>
) throws -> Regex<Output>.Match? {
try regex.program.loweredProgram.canOnlyMatchAtStart
? _match(input, in: subjectBounds, mode: .partialFromFront)
: _firstMatch(input, subjectBounds: subjectBounds, searchBounds: subjectBounds)
}
func _firstMatch(
_ input: String,
subjectBounds: Range<String.Index>,
searchBounds: Range<String.Index>
) throws -> Regex<Output>.Match? {
let executor = Executor(program: regex.program.loweredProgram)
let graphemeSemantic = regex.initialOptions.semanticLevel == .graphemeCluster
return try executor.firstMatch(
input,
subjectBounds: subjectBounds,
searchBounds: searchBounds,
graphemeSemantic: graphemeSemantic)
}
}
@available(SwiftStdlib 5.7, *)
extension BidirectionalCollection where SubSequence == Substring {
/// Returns a match if this string is matched by the given regex in its entirety.
///
/// - Parameter regex: The regular expression to match.
/// - Returns: The match, if one is found. If there is no match, or a
/// transformation in `regex` throws an error, this method returns `nil`.
public func wholeMatch<R: RegexComponent>(
of regex: R
) -> Regex<R.RegexOutput>.Match? {
try? regex.regex.wholeMatch(in: self[...])
}
/// Returns a match if this string is matched by the given regex at its start.
///
/// - Parameter regex: The regular expression to match.
/// - Returns: The match, if one is found. If there is no match, or a
/// transformation in `regex` throws an error, this method returns `nil`.
public func prefixMatch<R: RegexComponent>(
of regex: R
) -> Regex<R.RegexOutput>.Match? {
try? regex.regex.prefixMatch(in: self[...])
}
}
|