to-regex-range 0.1.0

Generate a compact regex that matches an integer range: (1, 99) -> [1-9]|[1-9][0-9]. A faithful port of the to-regex-range npm package. Zero dependencies, no_std.
Documentation
  • Coverage
  • 100%
    10 out of 10 items documented3 out of 7 items with examples
  • Size
  • Source code size: 30.41 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 213.75 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 3s Average build duration of successful builds.
  • all releases: 2s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • trananhtung/to-regex-range
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • trananhtung

to-regex-range

Crates.io Documentation CI License

Generate a compact regex that matches an integer range(1, 99)[1-9]|[1-9][0-9]. A faithful Rust port of the to-regex-range npm package (a micromatch building block). Zero dependencies and #![no_std].

use to_regex_range::{to_regex_range, to_regex_range_with_options, Options};

assert_eq!(to_regex_range(1, 5), "[1-5]");
assert_eq!(to_regex_range(1, 99), "(?:[1-9]|[1-9][0-9])");
assert_eq!(to_regex_range(0, 255), "(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])");
assert_eq!(to_regex_range(-10, -1), "(?:-[1-9]|-10)");

let opts = Options::default().shorthand(true);
assert_eq!(to_regex_range_with_options(1, 99, &opts), "(?:[1-9]|[1-9]\\d)");

Why to-regex-range?

Matching "a number between 1 and 255" with a regex by hand is tedious and error-prone. This builds the minimal alternation for you — splitting the range at power-of-ten boundaries and turning each sub-range into a character class with the right quantifier. The result is a regex source string; wrap it in your engine of choice (regex, fancy-regex, …).

[dependencies]
to-regex-range = "0.1"

API

Item Purpose
to_regex_range(min, max) The regex source for the range, default options
to_regex_range_with_options(min, max, &Options) …with options
Options { capture, shorthand, wrap } capture( … ); shorthand\d; wrap (default) → (?: … )

Behavior

  • min/max may be given in either order; equal bounds yield the literal number.
  • Negative ranges are handled, sharing a -? prefix where positive and negative sub-patterns coincide.
  • The output is a bare regex source — no anchors or delimiters. Add ^(?:…)$ if you need to match a whole string.
  • Integer ranges only; zero-padded ranges (e.g. 001..100) are out of scope.

License

Licensed under either of Apache-2.0 or MIT at your option.