Skip to content

Commit c219428

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

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-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: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
typealias MatchFunctionType = (String) throws -> Regex<AnyRegexOutput>.Match?
20+
21+
@Argument(help: "The regex pattern to test.")
22+
var pattern: String
23+
24+
@Argument(help: "One or more input strings to test against <pattern>.")
25+
var inputs: [String]
26+
27+
@Flag(
28+
name: [.customShort("p"), .customLong("partial")],
29+
help: "Allow partial matches.")
30+
var allowPartialMatch: Bool = false
31+
32+
mutating func run() throws {
33+
print("Using pattern \(pattern.halfWidthCornerQuoted)")
34+
let regex = try Regex(pattern)
35+
36+
for input in inputs {
37+
print("Input \(input.halfWidthCornerQuoted)")
38+
39+
let matchFunc: MatchFunctionType = allowPartialMatch
40+
? regex.firstMatch(in:)
41+
: regex.wholeMatch(in:)
42+
43+
if let result = try matchFunc(input) {
44+
print(" matched: \(result.0.halfWidthCornerQuoted)")
45+
} else {
46+
print(" no match")
47+
}
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)