Skip to content

Commit a506a3a

Browse files
committed
Add a simple command-line regex tester
1 parent a936e9e commit a506a3a

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Package.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,13 @@ let package = Package(
100100
"_RegexParser",
101101
"_StringProcessing"
102102
]),
103+
.executableTarget(
104+
name: "RegexTester",
105+
dependencies: [
106+
.product(name: "ArgumentParser", package: "swift-argument-parser"),
107+
"_RegexParser",
108+
"_StringProcessing"
109+
]),
103110

104111
// MARK: Exercises
105112
.target(

Sources/RegexTester/RegexTester.swift

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)