1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
//! # 🔮 Write readable regular expressions
//!
//! The crate provides a clean and readable way of writing your regex in the Rust programming language:
//!
//! <table>
//! <tr>
//! <td>
//!
//! Without `pretty_regex`
//!
//! </td>
//! <td>
//!
//! With `pretty_regex`
//!
//! </td>
//! </tr>
//!
//! <tr>
//! <td>
//!
//! ```reg
//! \d{5}(-\d{4})?
//! ```
//!
//! </td>
//! <td>
//!
//! ```ignore
//! digit()
//! .repeats(5)
//! .then(
//! just("-")
//! .then(digit().repeats(4))
//! .optional()
//! )
//! ```
//!
//! </td>
//! </tr>
//! <tr>
//! <td>
//!
//! ```reg
//! ^(?:\d){4,}(?:(?:\-)(?:\d){2,}){2,}$
//! ```
//!
//! </td>
//! <td>
//!
//! ```ignore
//! beginning()
//! .then(digit().repeats(4))
//! .then(
//! just("-")
//! .then(digit().repeats(2))
//! .repeats(2)
//! )
//! .then(ending())
//! ```
//!
//! </td>
//! </tr>
//!
//! <tr>
//! <td>
//!
//! ```reg
//! rege(x(es)?|xps?)
//! ```
//!
//! </td>
//! <td>
//!
//! ```ignore
//! just("rege")
//! .then(one_of(&[
//! just("x").then(just("es").optional()),
//! just("xp").then(just("s").optional()),
//! ]))
//! ```
//!
//! </td>
//! </tr>
//! </table>
//!
//! # How to use the crate?
//!
//! To convert a `PrettyRegex` struct which is constructed using all these `then`, `one_of`, `beginning`, `digit`, etc. functions into
//! a real regex (from `regex` crate), you can call `to_regex` or `to_regex_or_panic`:
//!
//! ```
//! use pretty_regex::digit;
//! let regex = digit().to_regex_or_panic();
//!
//! assert!(regex.is_match("3"));
//! ```
use regex::{escape, Regex};
use unicode::Category;
use std::{
fmt::Display,
marker::PhantomData,
ops::{Add, Range, RangeInclusive},
};
pub mod logic;
pub mod unicode;
pub use logic::*;
/// Represents the state when regular expression is for a single-character ASCII class
/// (the kind surrounded by colons and two layers of square brackets).
pub struct Ascii;
/// Represents the state when regular expression is for a custom single-character class
/// (the kind surrounded by one layer of square brackets).
pub struct Custom;
/// Represents the state when regular expression corresponds to a single-character character.
pub struct CharClass<T>(PhantomData<T>);
/// Represents the state when regular expression is a standard single-character class
/// (the kind in most cases starts with a backslash followed by a letter)
///
/// E.g. `\d`, `\p{Arabic}`.
pub struct Standart;
/// Represents the state when regular expression is a literal string of characters.
pub struct Text;
/// Represents the state when it is any arbitrary regular expression.
pub struct Chain;
/// Represents the state when regular expression is a quantifier (e.g., an expression
/// that matches a given number of a target).
///
/// These expressions are greedy by default and can be converted to a lazy match.
pub struct Quantifier;
pub struct PrettyRegex<T = Chain>(String, PhantomData<T>);
impl<T> PrettyRegex<T> {
/// Creates a new empty [`PrettyRegex`].
#[inline]
#[must_use]
pub fn new() -> Self {
Self(String::new(), PhantomData)
}
/// Converts the [`PrettyRegex`] into a real [`Regex`].
#[inline]
#[must_use]
pub fn to_regex(&self) -> Result<Regex, regex::Error> {
Regex::new(&self.0)
}
/// Converts the [`PrettyRegex`] into a real [`Regex`].
///
/// # Panics
///
/// If the regular expression is not valid.
#[inline]
#[must_use]
pub fn to_regex_or_panic(&self) -> Regex {
self.to_regex().unwrap()
}
/// Allows to chain [`PrettyRegex`].
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// let regex = just("a").then(just("b")).to_regex_or_panic();
///
/// assert!(regex.is_match("ab"));
/// assert!(!regex.is_match("ac"));
/// ```
#[inline]
#[must_use]
pub fn then<U>(self, then: PrettyRegex<U>) -> PrettyRegex<Chain> {
PrettyRegex::from(self.0 + &then.0)
}
}
impl<T, R> From<T> for PrettyRegex<R>
where
T: Into<String>,
{
fn from(value: T) -> Self {
Self(value.into(), PhantomData)
}
}
impl PrettyRegex<Quantifier> {
/// Adds a lazy modifier to [`Quantifier`].
///
/// ```
/// # use pretty_regex::just;
/// let regex = just("a").repeats_at_least(3).lazy();
/// ```
///
/// Not everything can be lazy. For instance, this spinnet of code doesn't
/// compile:
///
/// ```compile_fail
/// # use pretty_regex::just;
/// let regex = just("a").lazy();
/// ```
#[inline]
#[must_use]
pub fn lazy(&self) -> PrettyRegex<Chain> {
PrettyRegex::from(format!("{}?", self.0))
}
}
impl<T> From<PrettyRegex<T>> for Regex {
fn from(value: PrettyRegex<T>) -> Self {
value.to_regex().unwrap()
}
}
impl<L, R> Add<PrettyRegex<R>> for PrettyRegex<L> {
type Output = PrettyRegex<Chain>;
/// Allows to chain [`PrettyRegex`].
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// let regex = (just("a") + just("b")).to_regex_or_panic();
///
/// assert!(regex.is_match("ab"));
/// assert!(!regex.is_match("ac"));
/// ```
fn add(self, rhs: PrettyRegex<R>) -> Self::Output {
PrettyRegex::from(format!("{}{}", self, rhs))
}
}
impl<T> Display for PrettyRegex<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
/// Adds a matching text into a [`PrettyRegex`].
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// assert!(just("a").to_regex_or_panic().is_match("a"));
/// assert!(!just("a").to_regex_or_panic().is_match("b"));
/// ```
pub fn just(text: impl Into<String>) -> PrettyRegex<Text> {
PrettyRegex::from(format!("(?:{})", escape(&*text.into())))
}
/// Makes regex from unescaped text. It allows to add a regex string directly into a
/// [`PrettyRegex`] object.
///
/// # Example
///
/// ```
/// # use pretty_regex::nonescaped;
/// let regex = nonescaped(r"^\d$").to_regex_or_panic();
/// assert!(!regex.is_match("a"));
/// assert!(regex.is_match("2"));
/// ```
pub fn nonescaped(text: impl Into<String>) -> PrettyRegex<Chain> {
PrettyRegex::from(format!("(?:{})", &*text.into()))
}
/// Matches any character, except for newline (`\n`).
///
/// # Example
///
/// ```
/// # use pretty_regex::any;
/// assert!(!any().to_regex_or_panic().is_match("\n"));
/// assert!(any().to_regex_or_panic().is_match("a"));
/// ```
#[inline]
#[must_use]
pub fn any() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r".")
}
/// Matches digit character class (`\d`).
///
/// # Example
///
/// ```
/// # use pretty_regex::digit;
/// assert!(digit().to_regex_or_panic().is_match("1"));
/// assert!(digit().to_regex_or_panic().is_match("7"));
/// assert!(!digit().to_regex_or_panic().is_match("a"));
/// ```
#[inline]
#[must_use]
pub fn digit() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r"\d")
}
/// Matches word character class (`\w`) - any alphanumeric character or underscore (`_`).
///
/// # Example
///
/// ```
/// # use pretty_regex::word;
/// assert!(word().to_regex_or_panic().is_match("a"));
/// assert!(word().to_regex_or_panic().is_match("2"));
/// assert!(word().to_regex_or_panic().is_match("_"));
/// assert!(!word().to_regex_or_panic().is_match("?"));
/// ```
pub fn word() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r"\w")
}
/// Matches a word boundary (`\b`).
pub fn word_boundary() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r"\b")
}
/// Matches whitespace character class (`\s`).
///
/// # Example
///
/// ```
/// # use pretty_regex::whitespace;
/// assert!(whitespace().to_regex_or_panic().is_match("\n"));
/// assert!(whitespace().to_regex_or_panic().is_match(" "));
/// assert!(!whitespace().to_regex_or_panic().is_match("a"));
/// ```
pub fn whitespace() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r"\s")
}
/// Matches ascii alphabetic characters (`a-zA-Z`).
///
/// # Example
///
/// ```
/// # use pretty_regex::ascii_alphabetic;
/// assert!(ascii_alphabetic().to_regex_or_panic().is_match("a"));
/// assert!(ascii_alphabetic().to_regex_or_panic().is_match("B"));
/// assert!(!ascii_alphabetic().to_regex_or_panic().is_match("1"));
/// assert!(!ascii_alphabetic().to_regex_or_panic().is_match(" "));
/// ```
pub fn ascii_alphabetic() -> PrettyRegex<CharClass<Ascii>> {
PrettyRegex::from(r"[[:alpha:]]")
}
/// Matches ascii alphanumeric characters (`a-zA-Z0-9`).
///
/// # Example
///
/// ```
/// # use pretty_regex::ascii_alphanumeric;
/// assert!(ascii_alphanumeric().to_regex_or_panic().is_match("a"));
/// assert!(ascii_alphanumeric().to_regex_or_panic().is_match("Z"));
/// assert!(ascii_alphanumeric().to_regex_or_panic().is_match("7"));
/// assert!(!ascii_alphanumeric().to_regex_or_panic().is_match(" "));
/// ```
pub fn ascii_alphanumeric() -> PrettyRegex<CharClass<Ascii>> {
PrettyRegex::from(r"[[:alnum:]]")
}
/// Matches alphabetic characters (in `Letter` Unicode category).
///
/// # Example
///
/// ```
/// # use pretty_regex::alphabetic;
/// assert!(alphabetic().to_regex_or_panic().is_match("a"));
/// assert!(alphabetic().to_regex_or_panic().is_match("ÑŽ"));
/// assert!(alphabetic().to_regex_or_panic().is_match("A"));
/// assert!(!alphabetic().to_regex_or_panic().is_match("5"));
/// assert!(!alphabetic().to_regex_or_panic().is_match("!"));
/// ```
pub fn alphabetic() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(Category::Letter)
}
/// Matches alphanumeric characters (in `Letter` and `Number` Unicode categories).
///
/// # Example
///
/// ```
/// # use pretty_regex::alphanumeric;
/// assert!(alphanumeric().to_regex_or_panic().is_match("a"));
/// assert!(alphanumeric().to_regex_or_panic().is_match("ÑŽ"));
/// assert!(alphanumeric().to_regex_or_panic().is_match("A"));
/// assert!(alphanumeric().to_regex_or_panic().is_match("5"));
/// assert!(!alphanumeric().to_regex_or_panic().is_match("!"));
/// ```
pub fn alphanumeric() -> PrettyRegex<Chain> {
one_of(&[
PrettyRegex::from(Category::Letter),
PrettyRegex::from(Category::Number),
])
}
/// Matches lowercase characters (in `Lowercase_Letter` Unicode category).
///
/// # Example
///
/// ```
/// # use pretty_regex::lowercase;
/// assert!(lowercase().to_regex_or_panic().is_match("a"));
/// assert!(lowercase().to_regex_or_panic().is_match("ÑŽ"));
/// assert!(!lowercase().to_regex_or_panic().is_match("A"));
/// assert!(!lowercase().to_regex_or_panic().is_match("!"));
/// assert!(!lowercase().to_regex_or_panic().is_match(" "));
/// ```
#[inline]
#[must_use]
pub fn lowercase() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(Category::LowercaseLetter)
}
/// Matches ascii lowercase characters (`a-z`).
///
/// # Example
///
/// ```
/// # use pretty_regex::ascii_lowercase;
/// assert!(ascii_lowercase().to_regex_or_panic().is_match("a"));
/// assert!(ascii_lowercase().to_regex_or_panic().is_match("b"));
/// assert!(!ascii_lowercase().to_regex_or_panic().is_match("ÑŽ"));
/// assert!(!ascii_lowercase().to_regex_or_panic().is_match("A"));
/// assert!(!ascii_lowercase().to_regex_or_panic().is_match("!"));
/// assert!(!ascii_lowercase().to_regex_or_panic().is_match(" "));
/// ```
#[inline]
#[must_use]
pub fn ascii_lowercase() -> PrettyRegex<CharClass<Ascii>> {
PrettyRegex::from(r"[[:lower:]]")
}
/// Matches anything within a specified set of characters.
///
/// # Example
///
/// ```
/// # use pretty_regex::within;
/// assert!(within(&['a', 'b']).to_regex_or_panic().is_match("a"));
/// assert!(within(&['a', 'b']).to_regex_or_panic().is_match("b"));
/// assert!(!within(&['a', 'b']).to_regex_or_panic().is_match("c"));
#[inline]
#[must_use]
pub fn within<T>(set: &[T]) -> PrettyRegex<CharClass<Custom>>
where
T: Display,
{
PrettyRegex::from(format!(
"[{}]",
set.into_iter().map(|c| c.to_string()).collect::<String>()
))
}
/// Matches anything outside of a specified set of characters.
///
/// # Example
///
/// ```
/// # use pretty_regex::without;
/// assert!(!without(&['a', 'b']).to_regex_or_panic().is_match("a"));
/// assert!(!without(&['a', 'b']).to_regex_or_panic().is_match("b"));
/// assert!(without(&['a', 'b']).to_regex_or_panic().is_match("c"));
/// ```
#[inline]
#[must_use]
pub fn without<T>(set: &[T]) -> PrettyRegex<CharClass<Custom>>
where
T: Display,
{
PrettyRegex::from(format!(
"[^{}]",
set.into_iter().map(|c| c.to_string()).collect::<String>()
))
}
/// Matches characters within a given range.
///
/// # Example
///
/// ```
/// # use pretty_regex::within_char_range;
/// assert!(within_char_range('a'..='z').to_regex_or_panic().is_match("a"));
/// assert!(!within_char_range('a'..='z').to_regex_or_panic().is_match("Z"));
/// ```
#[inline]
#[must_use]
pub fn within_char_range(range: RangeInclusive<char>) -> PrettyRegex<CharClass<Custom>> {
PrettyRegex::from(format!("[{}-{}]", range.start(), range.end()))
}
/// Matches characters outside of a given range.
///
/// # Example
///
/// ```
/// # use pretty_regex::without_char_range;
/// assert!(!without_char_range('a'..='z').to_regex_or_panic().is_match("a"));
/// assert!(without_char_range('a'..='z').to_regex_or_panic().is_match("Z"));
/// ```
#[inline]
#[must_use]
pub fn without_char_range(range: RangeInclusive<char>) -> PrettyRegex<CharClass<Custom>> {
PrettyRegex::from(format!("[^{}-{}]", range.start(), range.end()))
}
/// Matches the beginning of the text or SOF with multi-line mode off (`^`).
///
/// # Example
///
/// ```
/// # use pretty_regex::{just, beginning};
/// let regex = beginning().then(just("foo")).to_regex_or_panic();
///
/// assert!(regex.is_match("foo"));
/// assert!(!regex.is_match("ffoo"));
/// ```
#[inline]
#[must_use]
pub fn beginning() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r"^")
}
/// Matches the end of the text or EOF with multi-line mode on (`$`).
///
/// # Example
///
/// ```
/// # use pretty_regex::{just, ending};
/// let regex = just("foo").then(ending()).to_regex_or_panic();
///
/// assert!(regex.is_match("foo"));
/// assert!(!regex.is_match("foof"));
/// ```
#[inline]
#[must_use]
pub fn ending() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r"$")
}
/// Matches the beginning of the text even with multi-line mode on (`\A`).
///
/// # Example
///
/// ```
/// # use pretty_regex::{just, text_beginning};
/// let regex = text_beginning().then(just("foo")).to_regex_or_panic();
///
/// assert!(regex.is_match("foo"));
/// assert!(!regex.is_match("ffoo"));
/// ```
#[inline]
#[must_use]
pub fn text_beginning() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r"\A")
}
/// Matches the end of the text even with multi-line mode on (`\z`).
///
/// # Example
///
/// ```
/// # use pretty_regex::{just, text_ending};
/// let regex = just("foo").then(text_ending()).to_regex_or_panic();
///
/// assert!(regex.is_match("foo"));
/// assert!(!regex.is_match("foof"));
/// ```
#[inline]
#[must_use]
pub fn text_ending() -> PrettyRegex<CharClass<Standart>> {
PrettyRegex::from(r"\z")
}
impl<T> PrettyRegex<T> {
/// Matches the pattern a given amount of times.
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// let regex = just("foo")
/// .repeats(3)
/// .to_regex_or_panic();
///
/// assert!(regex.is_match("foofoofoo"));
/// assert!(!regex.is_match("foo"));
/// assert!(!regex.is_match("bar"));
/// ```
#[inline]
#[must_use]
pub fn repeats(self, times: usize) -> PrettyRegex<Quantifier> {
PrettyRegex::from(format!("(?:{}){{{}}}", self, times))
}
/// Matches the pattern at least a given amount of times.
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// let regex = just("foo")
/// .repeats_at_least(2)
/// .to_regex_or_panic();
///
/// assert!(!regex.is_match("foo"));
/// assert!(regex.is_match("foofoo"));
/// assert!(!regex.is_match("bar"));
/// ```
#[inline]
#[must_use]
pub fn repeats_at_least(self, times: usize) -> PrettyRegex<Quantifier> {
PrettyRegex::from(format!("(?:{}){{{},}}", self, times))
}
/// Matches the pattern one or more times.
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// let regex = just("foo")
/// .repeats_one_or_more_times()
/// .to_regex_or_panic();
///
/// assert!(regex.is_match("foo"));
/// assert!(regex.is_match("foofoo"));
/// assert!(!regex.is_match("bar"));
/// ```
#[inline]
#[must_use]
pub fn repeats_one_or_more_times(self) -> PrettyRegex<Quantifier> {
PrettyRegex::from(format!("(?:{})+", self))
}
/// Matches the pattern optionally (zero or one time).
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// let regex = just("foo")
/// .optional()
/// .to_regex_or_panic();
///
/// assert!(regex.is_match(""));
/// assert!(regex.is_match("foo"));
/// ```
#[inline]
#[must_use]
pub fn optional(self) -> PrettyRegex<Quantifier> {
PrettyRegex::from(format!("(?:{})?", self))
}
/// Matches the pattern zero or more times.
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// let regex = just("foo")
/// .repeats_zero_or_more_times()
/// .to_regex_or_panic();
///
/// assert!(regex.is_match(""));
/// assert!(regex.is_match("foo"));
/// assert!(regex.is_match("foofoo"));
/// ```
#[inline]
#[must_use]
pub fn repeats_zero_or_more_times(self) -> PrettyRegex<Quantifier> {
PrettyRegex::from(format!("(?:{})*", self))
}
/// Matches the pattern `n` times where `n` is within a given range.
///
/// # Example
///
/// ```
/// # use pretty_regex::just;
/// let regex = just("f")
/// .repeats_n_times_within(3..5)
/// .to_regex_or_panic();
///
/// assert!(!regex.is_match("f"));
/// assert!(!regex.is_match("ff"));
/// assert!(regex.is_match("ffff"));
/// ```
#[inline]
#[must_use]
pub fn repeats_n_times_within(self, range: Range<usize>) -> PrettyRegex<Quantifier> {
PrettyRegex::from(format!("(?:{}){{{},{}}}", self, range.start, range.end))
}
/// Adds a capturnig group around a specific regular expression.
///
/// # Example
///
/// Let's say that we want to process simple date consisting of
/// month and day number. The problem is that we need to save the data
/// about these numbers to use it later. That's why we use captures!
///
/// It's important that "unnamed" captures can only be matched using numbers, which
/// are sequenced from left to right. The number depends on the order of the regular
/// expression in the chain.
///
/// ```
/// # use pretty_regex::{digit, just};
/// let regex = digit().repeats(2).unnamed_capture()
/// .then(just("-"))
/// .then(digit().repeats(2).unnamed_capture())
/// .to_regex_or_panic();
///
/// let captures = regex.captures("08-05").unwrap();
///
/// assert_eq!(captures.get(1).unwrap().as_str(), "08");
/// assert_eq!(captures.get(2).unwrap().as_str(), "05");
/// ```
pub fn unnamed_capture(self) -> PrettyRegex<Chain> {
PrettyRegex::from(format!("({})", self))
}
/// Adds a named capturing groupd around a specific regular expression.
///
/// # Example
///
/// Let's say that we want to process simple date consisting of
/// month and day number. The problem is that we need to save the data
/// about these numbers to use it later. That's why we use captures!
/// See [`PrettyRegex::unnamed_capture`] for more details.
///
/// Here we can give captures a specified names, to then match on them:
///
///
/// ```
/// # use pretty_regex::{digit, just};
/// let regex = digit().repeats(2).named_capture("month")
/// .then(just("-"))
/// .then(digit().repeats(2).named_capture("day"))
/// .to_regex_or_panic();
///
/// let captures = regex.captures("08-05").unwrap();
///
/// assert_eq!(&captures["month"], "08");
/// assert_eq!(&captures["day"], "05");
/// ```
pub fn named_capture(self, name: impl AsRef<str>) -> PrettyRegex<Chain> {
PrettyRegex::from(format!("(?P<{}>{})", name.as_ref(), self))
}
}
/// Establishes an OR relationship between regular expressions.
///
/// # Example
///
/// ```
/// # use pretty_regex::{one_of, just};
/// let regex = one_of(&[just("hi"), just("bar")]).to_regex_or_panic();
///
/// assert!(regex.is_match("hi"));
/// assert!(regex.is_match("bar"));
/// assert!(!regex.is_match("baz"));
/// ```
pub fn one_of<S>(options: &[S]) -> PrettyRegex<Chain>
where
S: Display,
{
let mut regex_string = format!("{}", options[0]);
for idx in 1..options.len() {
regex_string = format!("{}|{}", regex_string, options[idx])
}
PrettyRegex::from(regex_string)
}