|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// |
| 10 | +//===----------------------------------------------------------------------===// |
| 11 | + |
| 12 | +import ArgumentParser |
| 13 | +import _RegexParser |
| 14 | +import _StringProcessing |
| 15 | + |
| 16 | +@main |
| 17 | +@available(macOS 9999, *) |
| 18 | +struct RegexTester: ParsableCommand { |
| 19 | + @Argument(help: "The regex pattern to test.") |
| 20 | + var pattern: String |
| 21 | + |
| 22 | + @Argument(help: "One or more input strings to test against <pattern>.") |
| 23 | + var inputs: [String] |
| 24 | + |
| 25 | + @Flag( |
| 26 | + name: [.customShort("p"), .customLong("partial")], |
| 27 | + help: "Allow partial matches.") |
| 28 | + var allowPartialMatch: Bool = false |
| 29 | + |
| 30 | + lazy var regexResult: Result<Regex, ValidationError> = Result { |
| 31 | + try Regex(pattern) |
| 32 | + }.mapError { |
| 33 | + ValidationError("\($0)") |
| 34 | + } |
| 35 | + |
| 36 | + mutating func run() throws { |
| 37 | + print("Using pattern \(pattern.halfWidthCornerQuoted)") |
| 38 | + let regex = try regexResult.get() |
| 39 | + |
| 40 | + for input in inputs { |
| 41 | + print("Input \(input.halfWidthCornerQuoted)") |
| 42 | + |
| 43 | + let result: Regex<AnyRegexOutput>.Match |
| 44 | + if allowPartialMatch, let r = try regex.firstMatch(in: input) { |
| 45 | + result = r |
| 46 | + } else if !allowPartialMatch, let r = try regex.wholeMatch(in: input) { |
| 47 | + result = r |
| 48 | + } else { |
| 49 | + print(" no match") |
| 50 | + continue |
| 51 | + } |
| 52 | + |
| 53 | + print(" matched: \(result.0.halfWidthCornerQuoted)") |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments