Skip to content

Add a simple command-line regex tester #441

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,13 @@ let package = Package(
"_RegexParser",
"_StringProcessing"
]),
.executableTarget(
name: "RegexTester",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
"_RegexParser",
"_StringProcessing"
]),

// MARK: Exercises
.target(
Expand Down
50 changes: 50 additions & 0 deletions Sources/RegexTester/RegexTester.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

import ArgumentParser
import _RegexParser
import _StringProcessing

@main
@available(macOS 9999, *)
struct RegexTester: ParsableCommand {
typealias MatchFunctionType = (String) throws -> Regex<AnyRegexOutput>.Match?

@Argument(help: "The regex pattern to test.")
var pattern: String

@Argument(help: "One or more input strings to test against <pattern>.")
var inputs: [String]

@Flag(
name: [.customShort("p"), .customLong("partial")],
help: "Allow partial matches.")
var allowPartialMatch: Bool = false

mutating func run() throws {
print("Using pattern \(pattern.halfWidthCornerQuoted)")
let regex = try Regex(pattern)

for input in inputs {
print("Input \(input.halfWidthCornerQuoted)")

let matchFunc: MatchFunctionType = allowPartialMatch
? regex.firstMatch(in:)
: regex.wholeMatch(in:)

if let result = try matchFunc(input) {
print(" matched: \(result.0.halfWidthCornerQuoted)")
} else {
print(" no match")
}
}
}
}