sr

Find the shortest matching patterns for a given regex.

#!/usr/bin/python
"""
Generate strings that match a regular expression.

By default, this script uses the Greenery library to convert the supplied
regular expression into a finite-state machine and prints the shortest
matching strings first.

Installation:
    python -m pip install greenery

The optional -r mode generates random matching strings using Exrex. Install it
as well when random generation is required:
    python -m pip install exrex

Examples:
    # Print the shortest string matching the expression:
    python shortest_matches.py "a(b|c)*"

    # Print the five shortest matching strings:
    python shortest_matches.py -n 5 "a(b|c)*"

    # Print three randomly generated matching strings:
    python shortest_matches.py -r 3 "a(b|c)*"
"""

import sys
import argparse
import itertools

from greenery import parse

ap = argparse.ArgumentParser(description="matching strings for a regex")
ap.add_argument("regex")
ap.add_argument(
    "-n",
    type=int,
    default=1,
    help="show the N shortest matches, shortest-first (default 1)",
)
ap.add_argument(
    "-r",
    type=int,
    metavar="N",
    help="show N random matches (variety across branches)",
)
a = ap.parse_args()

if a.r is not None:
    import exrex

    for _ in range(a.r):
        print(exrex.getone(a.regex))
else:
    for s in itertools.islice(iter(parse(a.regex).to_fsm()), a.n):
        print(s)
download sr