fancy_regex/lib.rs
1// Copyright 2026 The Fancy Regex Authors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE.
20
21#![doc = include_str!("../docs/main.md")]
22#![doc = include_str!("../docs/features.md")]
23#![doc = include_str!("../docs/syntax.md")]
24#![doc = include_str!("../docs/oniguruma_compatibility.md")]
25#![doc = include_str!("../docs/subroutines/1_intro.md")]
26#![doc = include_str!("../docs/subroutines/2_flags.md")]
27#![doc = include_str!("../docs/subroutines/3_left_recursion.md")]
28#![doc = include_str!("../docs/subroutines/4_recursion.md")]
29#![doc = include_str!("../docs/absent.md")]
30#![deny(missing_docs)]
31#![deny(missing_debug_implementations)]
32#![cfg_attr(not(feature = "std"), no_std)]
33
34extern crate alloc;
35
36use alloc::borrow::Cow;
37use alloc::boxed::Box;
38use alloc::string::{String, ToString};
39use alloc::sync::Arc;
40use alloc::vec;
41use alloc::vec::Vec;
42
43use core::convert::TryFrom;
44use core::fmt;
45use core::fmt::{Debug, Formatter};
46use core::ops::{Index, Range};
47use core::str::FromStr;
48use regex_automata::meta::Regex as RaRegex;
49use regex_automata::util::captures::Captures as RaCaptures;
50use regex_automata::util::syntax::Config as SyntaxConfig;
51use regex_automata::Anchored as RaAnchored;
52use regex_automata::Input as RaInput;
53
54mod analyze;
55mod byte_set;
56mod bytes;
57mod compile;
58mod error;
59mod expand;
60mod input;
61mod optimize;
62mod parse;
63mod parse_flags;
64mod regexset;
65mod replacer;
66mod seek;
67mod to_hir;
68mod vm;
69
70use crate::analyze::can_compile_as_anchored;
71use crate::analyze::{analyze, AnalyzeContext};
72use crate::compile::{compile, CompileOptions};
73use crate::optimize::{optimize, OptimizeOptions};
74use crate::parse::{ExprTree, NamedGroups, Parser};
75use crate::parse_flags::*;
76#[cfg(feature = "leftmost_longest")]
77use crate::vm::OPTION_LEFTMOST_LONGEST;
78use crate::vm::{Prog, OPTION_FIND_NOT_EMPTY, OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH};
79
80use bit_set::BitSet;
81
82pub use crate::byte_set::ByteSet;
83pub use crate::bytes::MatchBytes;
84pub use crate::error::{CompileError, Error, ParseError, Result, RuntimeError};
85pub use crate::expand::Expander;
86pub use crate::input::{Input, RegexInput};
87pub use crate::regexset::{RegexSet, RegexSetMatch, RegexSetOptions};
88pub use crate::replacer::{NoExpand, Replacer, ReplacerRef};
89pub use crate::seek::seek_pattern_is_useful;
90
91/// Controls how the regex engine handles input encoding.
92///
93/// This enum represents the three valid combinations of the `utf8` and `unicode`
94/// flags in the underlying regex engine. Each variant has different trade-offs
95/// between input flexibility and character class semantics.
96///
97/// The default is [`BytesMode::Unicode`].
98///
99/// # Variants
100///
101/// ## `BytesMode::Unicode` (default)
102///
103/// - Input is expected to be valid UTF-8
104/// - `.` matches any Unicode scalar value (except `\n` unless `dot_matches_new_line` is set)
105/// - `\w`, `\d`, `\s` match Unicode characters
106/// - Unicode properties like `\p{Letter}` are available
107/// - Word boundaries (`\b`) are Unicode-aware
108///
109/// ## `BytesMode::Ascii`
110///
111/// - Input can be arbitrary bytes (no UTF-8 requirement)
112/// - `.` matches any single **byte** (except `\n` unless `dot_matches_new_line` is set)
113/// - `\w` matches `[a-zA-Z0-9_]` only (ASCII)
114/// - `\d` matches `[0-9]` only (ASCII)
115/// - `\s` matches ASCII whitespace only
116/// - Unicode properties are **not available**
117/// - Word boundaries (`\b`) use ASCII-only word characters
118///
119/// Use this mode when matching raw binary data or filenames that may contain
120/// non-UTF-8 bytes and you don't need Unicode character classes.
121///
122/// ## `BytesMode::UnicodeBytes`
123///
124/// - Input can be arbitrary bytes (no UTF-8 requirement)
125/// - `.` matches Unicode scalar values (sequences of valid UTF-8 bytes)
126/// - `\w`, `\d`, `\s` match Unicode characters
127/// - Unicode properties like `\p{Letter}` are available
128///
129/// Use this mode when the input may contain non-UTF-8 bytes but you still want
130/// Unicode-aware character classes. Note that `.` will **not** match individual
131/// non-UTF-8 bytes — it only matches valid UTF-8 codepoint sequences.
132#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
133pub enum BytesMode {
134 /// Unicode mode: input must be valid UTF-8, full Unicode support.
135 /// (utf8=true, unicode=true)
136 #[default]
137 Unicode,
138 /// ASCII bytes mode: `.` matches any byte, character classes are ASCII-only.
139 /// (utf8=false, unicode=false)
140 Ascii,
141 /// Unicode-aware bytes mode: input can be non-UTF-8, character classes
142 /// remain Unicode-aware. `.` matches Unicode scalar values only.
143 /// (utf8=false, unicode=true)
144 UnicodeBytes,
145}
146
147const MAX_RECURSION: usize = 64;
148
149// the public API
150
151/// A builder for a `Regex` to allow configuring options.
152#[derive(Debug)]
153pub struct RegexBuilder {
154 pattern: String,
155 options: RegexOptionsBuilder,
156}
157
158/// A builder for a `Regex` to allow configuring options.
159#[derive(Debug)]
160pub struct RegexOptionsBuilder {
161 options: RegexOptions,
162}
163
164/// A compiled regular expression.
165#[derive(Clone)]
166pub struct Regex {
167 inner: RegexImpl,
168 named_groups: Arc<NamedGroups>,
169}
170
171// Separate enum because we don't want to expose any of this
172#[derive(Clone)]
173enum RegexImpl {
174 // Do we want to box this? It's pretty big...
175 Wrap {
176 inner: RaRegex,
177 /// The original pattern which the regex was constructed from
178 pattern: String,
179 /// Some optimizations avoid the VM, but need to use an extra capture group to represent the match boundaries
180 explicit_capture_group_0: bool,
181 /// The actual pattern passed to regex-automata for delegation
182 delegated_pattern: String,
183 /// Group indices that are inside {0} (zero-repetition) quantifiers.
184 /// These groups never participate in matching, so their captures
185 /// return None even though they exist in the regex-automata engine
186 /// for correct group-counting.
187 zero_rep_groups: BitSet,
188 },
189 Fancy {
190 prog: Arc<Prog>,
191 n_groups: usize,
192 /// The original pattern which the regex was constructed from
193 pattern: String,
194 options: HardRegexRuntimeOptions,
195 },
196}
197
198/// A single match of a regex or group in an input text
199#[derive(Copy, Clone, Debug, Eq, PartialEq)]
200pub struct Match<'t> {
201 text: &'t str,
202 start: usize,
203 end: usize,
204}
205
206/// An iterator over all non-overlapping matches for a particular input.
207///
208/// The iterator yields a `Result<S::Match>`. The iterator stops when no more
209/// matches can be found.
210///
211/// `'r` is the lifetime of the compiled regular expression and `'t` is the
212/// lifetime of the matched input.
213#[derive(Debug)]
214pub struct Matches<'r, 't, S: input::Input + ?Sized> {
215 re: &'r Regex,
216 input: RegexInput<'t, S>,
217 last_match: Option<usize>,
218 last_skipped_empty: bool,
219}
220
221impl<'r, 't, S: input::Input + ?Sized> Matches<'r, 't, S> {
222 /// Return the underlying regex.
223 pub fn regex(&self) -> &'r Regex {
224 self.re
225 }
226
227 /// Return the text being searched.
228 pub fn text(&self) -> &'t S {
229 self.input.haystack()
230 }
231
232 /// Return the current search input configuration.
233 pub fn input(&self) -> &RegexInput<'t, S> {
234 &self.input
235 }
236
237 /// Adapted from the `regex` crate. Calls `find_from_pos`/`captures_from_pos` repeatedly.
238 /// Ignores empty matches immediately after a match.
239 /// Also passes a flag when skipping an empty match, so that \G wouldn't match at the new start position.
240 fn next_with<F, R>(&mut self, mut search: F) -> Option<Result<R>>
241 where
242 F: FnMut(&Regex, &RegexInput<'t, S>, u32) -> Result<Option<(R, (usize, usize))>>,
243 {
244 if self.input.is_done() {
245 return None;
246 }
247
248 let option_flags = if self.last_skipped_empty {
249 OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH
250 } else {
251 0
252 };
253
254 let pos = self.input.effective_start();
255 let (result, (match_start, match_end)) = match search(self.re, &self.input, option_flags) {
256 Err(error) => {
257 // Stop on first error: If an error is encountered, return it, and set the "last match position"
258 // to the string length, so that the next next() call will return None, to prevent an infinite loop.
259 self.input
260 .set_start(self.input.get_range().end.saturating_add(1));
261 return Some(Err(error));
262 }
263 Ok(None) => return None,
264 Ok(Some(pair)) => pair,
265 };
266
267 if match_start == match_end {
268 // This is an empty match. To ensure we make progress, start
269 // the next search at the smallest possible starting position
270 // of the next match following this one.
271 self.input
272 .set_start(self.input.haystack().advance_position(match_end));
273 // Only set OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH on the next call if this was a
274 // truly zero-length match (the VM consumed no bytes from `pos`).
275 // This means that \K won't prevent \G from matching.
276 self.last_skipped_empty = match_end == pos;
277 // Don't accept empty matches immediately following a match.
278 // Just move on to the next match.
279 if Some(match_end) == self.last_match {
280 return self.next_with(search);
281 }
282 } else {
283 self.input.set_start(match_end);
284 self.last_skipped_empty = false;
285 }
286
287 self.last_match = Some(match_end);
288
289 Some(Ok(result))
290 }
291}
292
293impl<'r, 't, S: input::Input + ?Sized> Iterator for Matches<'r, 't, S> {
294 type Item = Result<S::Match<'t>>;
295
296 fn next(&mut self) -> Option<Self::Item> {
297 let text = self.input.haystack();
298 self.next_with(move |re, input, flags| {
299 re.find_input_raw(input, flags)
300 .map(|opt| opt.map(|(s, e)| (text.make_match(s, e), (s, e))))
301 })
302 }
303}
304
305/// An iterator that yields all non-overlapping capture groups matching a
306/// particular regular expression.
307///
308/// The iterator stops when no more matches can be found.
309///
310/// `'r` is the lifetime of the compiled regular expression and `'t` is the
311/// lifetime of the matched string.
312#[derive(Debug)]
313pub struct CaptureMatches<'r, 't, S: input::Input + ?Sized>(Matches<'r, 't, S>);
314
315impl<'r, 't, S: input::Input + ?Sized> CaptureMatches<'r, 't, S> {
316 /// Return the text being searched.
317 pub fn text(&self) -> &'t S {
318 self.0.input.haystack()
319 }
320
321 /// Return the underlying regex.
322 pub fn regex(&self) -> &'r Regex {
323 self.0.re
324 }
325}
326
327impl<'r, 't, S: input::Input + ?Sized> Iterator for CaptureMatches<'r, 't, S> {
328 type Item = Result<Captures<'t, S>>;
329
330 fn next(&mut self) -> Option<Self::Item> {
331 self.0.next_with(move |re, input, flags| {
332 let captures = re.captures_input_with_option_flags(input, flags)?;
333 Ok(captures.map(|c| {
334 let (start, end) = c
335 .inner
336 .get_span(0)
337 .expect("`Captures` is expected to have entire match at 0th position");
338 (c, (start, end))
339 }))
340 })
341 }
342}
343
344/// A set of capture groups found for a regex.
345///
346/// `S` is the input type (`str` or `[u8]`).
347#[derive(Debug)]
348pub struct Captures<'t, S: input::Input + ?Sized> {
349 inner: CapturesImpl,
350 named_groups: Arc<NamedGroups>,
351 input: &'t S,
352}
353
354#[derive(Debug)]
355enum CapturesImpl {
356 Wrap {
357 locations: RaCaptures,
358 /// Some optimizations avoid the VM but need an extra capture group to represent the match boundaries.
359 /// Therefore what is actually capture group 1 should be treated as capture group 0, and all other
360 /// capture groups should have their index reduced by one as well to line up with what the pattern specifies.
361 explicit_capture_group_0: bool,
362 /// Group indices that are inside {0} (zero-repetition) quantifiers.
363 /// These groups never participate in matching, so their captures return None.
364 zero_rep_groups: BitSet,
365 },
366 Fancy {
367 saves: Vec<usize>,
368 },
369}
370
371impl CapturesImpl {
372 fn get_span(&self, i: usize) -> Option<(usize, usize)> {
373 match self {
374 CapturesImpl::Wrap {
375 locations,
376 explicit_capture_group_0,
377 zero_rep_groups,
378 } => {
379 if zero_rep_groups.contains(i) {
380 return None;
381 }
382 locations
383 .get_group(i + if *explicit_capture_group_0 { 1 } else { 0 })
384 .map(|span| (span.start, span.end))
385 }
386 CapturesImpl::Fancy { saves } => {
387 let slot = i * 2;
388 if slot >= saves.len() {
389 return None;
390 }
391 let lo = saves[slot];
392 if lo == usize::MAX {
393 return None;
394 }
395 let hi = saves[slot + 1];
396 Some((lo, hi))
397 }
398 }
399 }
400
401 fn len(&self) -> usize {
402 match self {
403 CapturesImpl::Wrap {
404 locations,
405 explicit_capture_group_0,
406 ..
407 } => locations.group_len() - if *explicit_capture_group_0 { 1 } else { 0 },
408 CapturesImpl::Fancy { saves } => saves.len() / 2,
409 }
410 }
411}
412
413/// Iterator for captured groups in order in which they appear in the regex.
414#[derive(Debug)]
415pub struct SubCaptureMatches<'c, 't, S: input::Input + ?Sized> {
416 data: &'c Captures<'t, S>,
417 i: usize,
418}
419
420/// An iterator over all substrings delimited by a regex.
421///
422/// This iterator yields `Result<&'h str>`, where each item is a substring of the
423/// target string that is delimited by matches of the regular expression. It stops when there
424/// are no more substrings to yield.
425///
426/// `'r` is the lifetime of the compiled regular expression, and `'h` is the
427/// lifetime of the target string being split.
428///
429/// This iterator can be created by the [`Regex::split`] method.
430#[derive(Debug)]
431pub struct Split<'r, 'h> {
432 matches: Matches<'r, 'h, str>,
433 next_start: usize,
434 target: &'h str,
435}
436
437impl<'r, 'h> Iterator for Split<'r, 'h> {
438 type Item = Result<&'h str>;
439
440 /// Returns the next substring that results from splitting the target string by the regex.
441 ///
442 /// If no more matches are found, returns the remaining part of the string,
443 /// or `None` if all substrings have been yielded.
444 fn next(&mut self) -> Option<Result<&'h str>> {
445 match self.matches.next() {
446 None => {
447 let len = self.target.len();
448 if self.next_start > len {
449 // No more substrings to return
450 None
451 } else {
452 // Return the last part of the target string
453 // Next call will return None
454 let part = &self.target[self.next_start..len];
455 self.next_start = len + 1;
456 Some(Ok(part))
457 }
458 }
459 // Return the next substring
460 Some(Ok(m)) => {
461 let part = &self.target[self.next_start..m.start()];
462 self.next_start = m.end();
463 Some(Ok(part))
464 }
465 Some(Err(e)) => Some(Err(e)),
466 }
467 }
468}
469
470impl<'r, 'h> core::iter::FusedIterator for Split<'r, 'h> {}
471
472/// An iterator over at most `N` substrings delimited by a regex.
473///
474/// This iterator yields `Result<&'h str>`, where each item is a substring of the
475/// target that is delimited by matches of the regular expression. It stops either when
476/// there are no more substrings to yield, or after `N` substrings have been yielded.
477///
478/// The `N`th substring is the remaining part of the target.
479///
480/// `'r` is the lifetime of the compiled regular expression, and `'h` is the
481/// lifetime of the target string being split.
482///
483/// This iterator can be created by the [`Regex::splitn`] method.
484#[derive(Debug)]
485pub struct SplitN<'r, 'h> {
486 splits: Split<'r, 'h>,
487 limit: usize,
488}
489
490impl<'r, 'h> Iterator for SplitN<'r, 'h> {
491 type Item = Result<&'h str>;
492
493 /// Returns the next substring resulting from splitting the target by the regex,
494 /// limited to `N` splits.
495 ///
496 /// Returns `None` if no more matches are found or if the limit is reached after yielding
497 /// the remaining part of the target.
498 fn next(&mut self) -> Option<Result<&'h str>> {
499 if self.limit == 0 {
500 // Limit reached. No more substrings available.
501 return None;
502 }
503
504 // Decrement the limit for each split.
505 self.limit -= 1;
506 if self.limit > 0 {
507 return self.splits.next();
508 }
509
510 // Nth split
511 let len = self.splits.target.len();
512 if self.splits.next_start > len {
513 // No more substrings available.
514 None
515 } else {
516 // Return the remaining part of the target
517 let start = self.splits.next_start;
518 self.splits.next_start = len + 1;
519 Some(Ok(&self.splits.target[start..len]))
520 }
521 }
522
523 fn size_hint(&self) -> (usize, Option<usize>) {
524 (0, Some(self.limit))
525 }
526}
527
528impl<'r, 'h> core::iter::FusedIterator for SplitN<'r, 'h> {}
529
530#[derive(Clone)]
531struct RegexOptions {
532 syntaxc: SyntaxConfig,
533 delegate_size_limit: Option<usize>,
534 delegate_dfa_size_limit: Option<usize>,
535 delegate_dfa_skip_cache_capacity_check: bool,
536 /// Optional cap on the number of VM instructions emitted while compiling.
537 /// Subroutine calls are inlined at compile time, so a self- or
538 /// mutually-recursive pattern can expand without bound even while the
539 /// recursion-depth cap is respected; this bounds the emitted instruction
540 /// vector instead. `None` disables the check.
541 max_prog_size: Option<usize>,
542 oniguruma_mode: bool,
543 ignore_numbered_groups_when_named_groups_exist: bool,
544 hard_regex_runtime_options: HardRegexRuntimeOptions,
545 bytes_mode: BytesMode,
546 seek_filter: Option<fn(&str) -> bool>,
547 /// Whether the top-level engine of an easy (`Wrap`) pattern should build a
548 /// prefilter. `RegexSet` turns this off for its internally-built members:
549 /// the set only ever searches them anchored at candidate positions, where
550 /// a prefilter is never consulted, so building one wastes time and memory.
551 delegate_prefilter: bool,
552 /// Whether the expression tree should be optimized before analysis/compilation.
553 /// When disabled, the parsed expression is compiled as-is, without the
554 /// KeepOut/\K, trailing-lookahead, and nested-repeat rewrites that `optimize`
555 /// performs. This is mainly useful for differential testing: it lets callers
556 /// compare a pattern against its optimized form, or compile a pattern without
557 /// optimization entirely.
558 optimize: bool,
559 #[cfg(feature = "leftmost_longest")]
560 leftmost_longest: bool,
561}
562
563impl fmt::Debug for RegexOptions {
564 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
565 let seek_filter_desc = match self.seek_filter {
566 None => "None",
567 Some(f_ptr) if (f_ptr as *const ()) == (seek_pattern_is_useful as *const ()) => {
568 "Some(seek_pattern_is_useful)"
569 }
570 Some(_) => "Some(<custom>)",
571 };
572 let mut debug = f.debug_struct("RegexOptions");
573 debug
574 .field("syntaxc", &self.syntaxc)
575 .field("delegate_size_limit", &self.delegate_size_limit)
576 .field("delegate_dfa_size_limit", &self.delegate_dfa_size_limit)
577 .field(
578 "delegate_dfa_skip_cache_capacity_check",
579 &self.delegate_dfa_skip_cache_capacity_check,
580 )
581 .field("max_prog_size", &self.max_prog_size)
582 .field("oniguruma_mode", &self.oniguruma_mode)
583 .field(
584 "ignore_numbered_groups_when_named_groups_exist",
585 &self.ignore_numbered_groups_when_named_groups_exist,
586 )
587 .field(
588 "hard_regex_runtime_options",
589 &self.hard_regex_runtime_options,
590 )
591 .field("seek_filter", &seek_filter_desc)
592 .field("delegate_prefilter", &self.delegate_prefilter)
593 .field("optimize", &self.optimize);
594 #[cfg(feature = "leftmost_longest")]
595 debug.field("leftmost_longest", &self.leftmost_longest);
596 debug.finish()
597 }
598}
599
600impl Default for RegexOptions {
601 fn default() -> Self {
602 RegexOptions {
603 syntaxc: SyntaxConfig::new().unicode(true),
604 delegate_size_limit: None,
605 delegate_dfa_size_limit: None,
606 delegate_dfa_skip_cache_capacity_check: true,
607 max_prog_size: None,
608 oniguruma_mode: false,
609 ignore_numbered_groups_when_named_groups_exist: false,
610 hard_regex_runtime_options: HardRegexRuntimeOptions::default(),
611 bytes_mode: BytesMode::default(),
612 seek_filter: None, // when we are ready to enable seek by default, use: `Some(seek_pattern_is_useful)`
613 delegate_prefilter: true,
614 optimize: true,
615 #[cfg(feature = "leftmost_longest")]
616 leftmost_longest: false,
617 }
618 }
619}
620
621#[derive(Copy, Clone, Debug)]
622struct HardRegexRuntimeOptions {
623 backtrack_limit: usize,
624 find_not_empty: bool,
625 disallow_empty_match_at_eof_after_newline: bool,
626 allow_input_assertion_overrides: bool,
627 #[cfg(feature = "leftmost_longest")]
628 leftmost_longest: bool,
629}
630
631impl RegexOptions {
632 fn get_flag_value(flag_value: bool, enum_value: u32) -> u32 {
633 if flag_value {
634 enum_value
635 } else {
636 0
637 }
638 }
639
640 /// Whether the parsed expression tree should be run through the optimization
641 /// pass before analysis/compilation. The optimization is skipped when the
642 /// user has explicitly disabled it via
643 /// `RegexOptionsBuilder::optimize(false)`. When `find_not_empty` is set the
644 /// pass still runs, but `optimize()` is told to skip the KeepOut and
645 /// trailing-lookahead rewrites (which would make the pattern
646 /// delegatable, and the Wrap path can't reject empty matches).
647 fn should_optimize(&self) -> bool {
648 self.optimize
649 }
650
651 fn compute_flags(&self) -> u32 {
652 let insensitive = Self::get_flag_value(self.syntaxc.get_case_insensitive(), FLAG_CASEI);
653 let multiline = Self::get_flag_value(self.syntaxc.get_multi_line(), FLAG_MULTI);
654 let whitespace =
655 Self::get_flag_value(self.syntaxc.get_ignore_whitespace(), FLAG_IGNORE_SPACE);
656 let dotnl = Self::get_flag_value(self.syntaxc.get_dot_matches_new_line(), FLAG_DOTNL);
657 let unicode = Self::get_flag_value(
658 self.syntaxc.get_unicode() && !matches!(self.bytes_mode, BytesMode::Ascii),
659 FLAG_UNICODE,
660 );
661 let oniguruma_mode = Self::get_flag_value(self.oniguruma_mode, FLAG_ONIGURUMA_MODE);
662 let crlf = Self::get_flag_value(self.syntaxc.get_crlf(), FLAG_CRLF);
663 let named_groups_only = Self::get_flag_value(
664 self.ignore_numbered_groups_when_named_groups_exist,
665 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
666 );
667
668 insensitive
669 | multiline
670 | whitespace
671 | dotnl
672 | unicode
673 | oniguruma_mode
674 | crlf
675 | named_groups_only
676 }
677}
678
679impl Default for HardRegexRuntimeOptions {
680 fn default() -> Self {
681 HardRegexRuntimeOptions {
682 backtrack_limit: 1_000_000,
683 find_not_empty: false,
684 disallow_empty_match_at_eof_after_newline: false,
685 allow_input_assertion_overrides: false,
686 #[cfg(feature = "leftmost_longest")]
687 leftmost_longest: false,
688 }
689 }
690}
691
692impl Default for RegexOptionsBuilder {
693 fn default() -> Self {
694 Self::new()
695 }
696}
697
698impl RegexOptionsBuilder {
699 /// Create a new regex options builder.
700 pub fn new() -> Self {
701 RegexOptionsBuilder {
702 options: RegexOptions::default(),
703 }
704 }
705
706 /// Build a `Regex` from the given pattern.
707 ///
708 /// Returns an [`Error`](enum.Error.html) if the pattern could not be parsed.
709 pub fn build(&self, pattern: String) -> Result<Regex> {
710 Regex::new_options(pattern, &self.options)
711 }
712
713 fn set_config(&mut self, func: impl Fn(SyntaxConfig) -> SyntaxConfig) -> &mut Self {
714 self.options.syntaxc = func(self.options.syntaxc);
715 self
716 }
717
718 /// Override default case insensitive
719 /// this is to enable/disable casing via builder instead of a flag within
720 /// the raw string pattern which will be parsed
721 ///
722 /// Default is false
723 pub fn case_insensitive(&mut self, yes: bool) -> &mut Self {
724 self.set_config(|x| x.case_insensitive(yes))
725 }
726
727 /// Enable multi-line regex
728 pub fn multi_line(&mut self, yes: bool) -> &mut Self {
729 self.set_config(|x| x.multi_line(yes))
730 }
731
732 /// Allow ignore whitespace
733 pub fn ignore_whitespace(&mut self, yes: bool) -> &mut Self {
734 self.set_config(|x| x.ignore_whitespace(yes))
735 }
736
737 /// Enable or disable the "dot matches any character" flag.
738 /// When this is enabled, `.` will match any character. When it's disabled, then `.` will match any character
739 /// except for a new line character.
740 pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut Self {
741 self.set_config(|x| x.dot_matches_new_line(yes))
742 }
743
744 /// Enable or disable the CRLF mode flag (`R`).
745 ///
746 /// When enabled, `\r\n` is treated as a single line ending for the purposes of
747 /// `^` and `$` in multi-line mode, instead of treating `\r` and `\n` as separate
748 /// line endings.
749 ///
750 /// By default, this is disabled. It may be selectively enabled in the regular
751 /// expression by using the `R` flag, e.g. `(?mR)` or `(?Rm)`.
752 pub fn crlf(&mut self, yes: bool) -> &mut Self {
753 self.set_config(|x| x.crlf(yes))
754 }
755
756 /// Enable verbose mode in the regular expression.
757 ///
758 /// The same as ignore_whitespace
759 ///
760 /// When enabled, verbose mode permits insigificant whitespace in many
761 /// places in the regular expression, as well as comments. Comments are
762 /// started using `#` and continue until the end of the line.
763 ///
764 /// By default, this is disabled. It may be selectively enabled in the
765 /// regular expression by using the `x` flag regardless of this setting.
766 pub fn verbose_mode(&mut self, yes: bool) -> &mut Self {
767 self.set_config(|x| x.ignore_whitespace(yes))
768 }
769
770 /// Enable or disable the Unicode flag (`u`) by default.
771 ///
772 /// By default this is **enabled**. The inline `u` flag inside a pattern
773 /// is only accepted when it **matches** the current builder setting (e.g.
774 /// `(?u)` when unicode is already enabled, or `(?-u)` when it is already
775 /// disabled). Attempts to change the mode inline are rejected with a
776 /// [`ParseError::ChangingUnicodeModeUnsupported`] error. Use this builder
777 /// method to set the desired mode instead.
778 ///
779 /// ## Effect on `str` input (default)
780 ///
781 /// When matching against `&str` (the default), the underlying engine
782 /// requires that all matches respect UTF-8 boundaries. Disabling Unicode
783 /// therefore has the following effects:
784 ///
785 /// - **`\w`, `\d`, `\s`** become ASCII-only (`[a-zA-Z0-9_]`, `[0-9]`,
786 /// and ASCII whitespace respectively).
787 /// - **`\W`, `\D`, `\S`**, bare **`.`**, and **`\p{...}`** Unicode
788 /// properties **fail to compile**, because they could match byte
789 /// sequences that violate UTF-8 boundaries.
790 ///
791 /// If you need those constructs with `unicode_mode(false)`, use the bytes
792 /// API with [`BytesMode::Ascii`] instead.
793 ///
794 /// ## Effect on byte input
795 ///
796 /// When matching against `&[u8]` (via [`BytesMode::Ascii`]), all
797 /// constructs work as expected in ASCII mode (`.` matches any byte,
798 /// `\W`/`\D`/`\S` match non-ASCII byte values, etc.).
799 ///
800 /// **WARNING**: Unicode mode can greatly increase the size of the compiled
801 /// DFA, which can noticeably impact both memory usage and compilation
802 /// time. This is especially noticeable if your regex contains character
803 /// classes like `\w` that are impacted by whether Unicode is enabled or
804 /// not. If Unicode is not necessary, you are encouraged to disable it.
805 pub fn unicode_mode(&mut self, yes: bool) -> &mut Self {
806 self.set_config(|x| x.unicode(yes))
807 }
808
809 /// Limit for how many times backtracking should be attempted for fancy regexes (where
810 /// backtracking is used). If this limit is exceeded, execution returns an error with
811 /// [`Error::BacktrackLimitExceeded`](enum.Error.html#variant.BacktrackLimitExceeded).
812 /// This is for preventing a regex with catastrophic backtracking to run for too long.
813 ///
814 /// Default is `1_000_000` (1 million).
815 pub fn backtrack_limit(&mut self, limit: usize) -> &mut Self {
816 self.options.hard_regex_runtime_options.backtrack_limit = limit;
817 self
818 }
819
820 /// Set the approximate size limit of the compiled regular expression.
821 ///
822 /// This option is forwarded from the wrapped `regex` crate. Note that depending on the used
823 /// regex features there may be multiple delegated sub-regexes fed to the `regex` crate. As
824 /// such the actual limit is closer to `<number of delegated regexes> * delegate_size_limit`.
825 pub fn delegate_size_limit(&mut self, limit: usize) -> &mut Self {
826 self.options.delegate_size_limit = Some(limit);
827 self
828 }
829
830 /// Set the approximate capacity, in bytes, of the cache used by the lazy DFA of delegated
831 /// regexes.
832 ///
833 /// This corresponds to `hybrid_cache_capacity` in regex-automata, and has the same meaning as
834 /// `RegexBuilder::dfa_size_limit` in the `regex` crate. Note that depending on the used
835 /// regex features there may be multiple delegated sub-regexes. As such the actual limit is
836 /// closer to `<number of delegated regexes> * delegate_dfa_size_limit`.
837 ///
838 /// Patterns with a variable-length lookbehind additionally build a dedicated reverse lazy
839 /// DFA. If the limit is below the minimum cache capacity that DFA needs (which depends on the
840 /// NFA size of the lookbehind body and can reach several MiB to tens of MiB for large
841 /// repetitions of Unicode classes), it is rounded up to that minimum instead of causing a
842 /// compile error.
843 pub fn delegate_dfa_size_limit(&mut self, limit: usize) -> &mut Self {
844 self.options.delegate_dfa_size_limit = Some(limit);
845 self
846 }
847
848 /// Configure whether the reverse lazy DFA built for a variable-length lookbehind may exceed
849 /// the limit set by [`delegate_dfa_size_limit`](Self::delegate_dfa_size_limit) (or the
850 /// default) when it needs a larger minimum cache capacity.
851 ///
852 /// When `true` (the default), the cache capacity is rounded up to the minimum that the DFA
853 /// requires. When `false`, the limit is strictly honoured and a pattern whose DFA needs more
854 /// capacity fails to compile with [`CompileError::DfaBuildError`]. Like
855 /// [`RegexSetOptions::overlapping_dfa_skip_cache_capacity_check`], this only affects DFAs
856 /// that fancy-regex builds itself; ordinary delegated sub-regexes are unaffected.
857 pub fn delegate_dfa_skip_cache_capacity_check(&mut self, yes: bool) -> &mut Self {
858 self.options.delegate_dfa_skip_cache_capacity_check = yes;
859 self
860 }
861
862 /// Set the maximum number of VM instructions the compiled program may
863 /// contain. Subroutine calls are inlined at compile time, so a self- or
864 /// mutually-recursive pattern can expand without bound even while the
865 /// recursion-depth cap is respected; this bounds the emitted instruction
866 /// vector instead. If exceeded, compilation returns
867 /// `CompileError::PatternTooComplex`. `None` (the default) disables the
868 /// check, preserving the previous behavior.
869 pub fn max_prog_size(&mut self, limit: usize) -> &mut Self {
870 self.options.max_prog_size = Some(limit);
871 self
872 }
873
874 /// Require that matches are non-empty (i.e. match at least one character).
875 ///
876 /// When this is enabled, any match attempt that would result in a zero-length match is
877 /// rejected. The rejection happens on the VM path, so any sub-expression that could
878 /// produce an empty match is promoted to `hard` during analysis and the whole pattern is
879 /// compiled to the VM — the delegated (`Wrap`) path has no way to reject empty matches.
880 ///
881 /// Default is `false`.
882 ///
883 /// N.B. When `find_not_empty` is set and analysis determines the pattern will only ever
884 /// produce an empty match, compiling the regex will return
885 /// `CompileError::PatternCanNeverMatch` instead of silently constructing a regex that can never
886 /// return a result. This catches the user error at compile time rather than allowing the
887 /// combination to execute pointlessly at runtime.
888 ///
889 /// N.B. Because the pattern must stay on the VM, the KeepOut (`\K`) and trailing
890 /// positive-lookahead rewrites are skipped during optimization when `find_not_empty` is set
891 /// (see `OptimizeOptions` in `fancy_regex::internal`): both wrap the prefix in an explicit
892 /// capture group 0, which is what would otherwise flip `info.hard` to `false` and let the
893 /// pattern delegate to regex-automata. The safe rewrites (nested-repeat simplification and
894 /// ambiguous-concat-repeat rewriting) are still applied.
895 pub fn find_not_empty(&mut self, yes: bool) -> &mut Self {
896 self.options.hard_regex_runtime_options.find_not_empty = yes;
897 self
898 }
899
900 /// Enable or disable the expression-tree optimization pass.
901 ///
902 /// When enabled (the default), the parsed expression tree is rewritten before
903 /// analysis/compilation. The rewrite has two tiers (see
904 /// [`OptimizeOptions`](crate::internal::OptimizeOptions)):
905 ///
906 /// - **Always applied**: nested-repeat simplification and ambiguous-concat-repeat
907 /// rewriting.
908 /// - **Skipped when `find_not_empty` is set**: KeepOut (`\K`) and trailing
909 /// positive-lookahead hoisting, because both would make the pattern
910 /// delegatable and the delegated path can't reject empty matches.
911 ///
912 /// When disabled, the tree is compiled as-is.
913 ///
914 /// This is primarily intended for differential testing, where comparing a
915 /// pattern against its optimized form (or against a non-optimized build)
916 /// helps verify that the optimization preserves match semantics.
917 ///
918 /// Disabling this flag also affects the prefilter helpers
919 /// ([`start_bytes`](Self::start_bytes) and
920 /// [`required_bytes`](Self::required_bytes)): they analyze the same tree
921 /// that would be compiled, so with optimization disabled they report the
922 /// start/required bytes of the un-optimized tree.
923 ///
924 /// Default is `true`.
925 pub fn optimize(&mut self, yes: bool) -> &mut Self {
926 self.options.optimize = yes;
927 self
928 }
929
930 /// Enable leftmost-longest match semantics.
931 ///
932 /// When enabled, among all matches starting at the leftmost possible position,
933 /// the longest match is returned. This contrasts with the default leftmost-first
934 /// (PCRE-style) semantics.
935 ///
936 /// Default is `false`.
937 ///
938 /// **Note:** This requires the `leftmost_longest` feature to be enabled.
939 #[cfg(feature = "leftmost_longest")]
940 pub fn leftmost_longest(&mut self, yes: bool) -> &mut Self {
941 self.options.leftmost_longest = yes;
942 self.options.hard_regex_runtime_options.leftmost_longest = yes;
943 self
944 }
945
946 /// Treat unnamed capture groups as non-capturing when named groups exist.
947 /// Prevents accessing capture groups by number from within the pattern
948 /// (backrefs, subroutine calls) when named groups are present.
949 pub fn ignore_numbered_groups_when_named_groups_exist(&mut self, yes: bool) -> &mut Self {
950 self.options.ignore_numbered_groups_when_named_groups_exist = yes;
951 self
952 }
953
954 /// ⚠️ Experimental: This API may change, be removed without notice, or cause matches to be
955 /// skipped. This requires more real-world testing to prove correctness and observe in which
956 /// circumstances it brings performance benefits and in which it has the opposite effect.
957 /// Feedback (and benchmarks on real-world patterns/haystacks) would be very welcome!
958 ///
959 /// Enable the Seek pre-filter optimization for hard (backtracking) patterns.
960 ///
961 /// When enabled, the compiler attempts to derive a regular approximation of the pattern
962 /// which is used to skip to the earliest plausible match position in the haystack before
963 /// invoking the backtracking VM. This can dramatically speed up searches in long haystacks
964 /// when the pattern can only match at infrequent positions.
965 ///
966 /// The seek pattern is always a conservative over-approximation — it may report false-positive
967 /// positions but will never skip a true match.
968 ///
969 /// When `yes` is `true`, uses the default [`seek_pattern_is_useful`] filter to decide
970 /// whether the derived pattern is worth using. When `false`, disables seek entirely.
971 ///
972 /// To supply a custom filter, use [`seek_filter`](Self::seek_filter) instead.
973 pub fn seek(&mut self, yes: bool) -> &mut Self {
974 self.options.seek_filter = if yes {
975 Some(seek_pattern_is_useful)
976 } else {
977 None
978 };
979 self
980 }
981
982 /// Set a custom filter function that decides whether the derived seek pattern is useful.
983 ///
984 /// The function receives the seek pattern string and returns `true` if the pattern should
985 /// be used as a pre-filter, or `false` to fall back to the standard unanchored search.
986 ///
987 /// Calling this method implicitly enables seek. Pass [`seek_pattern_is_useful`] to restore
988 /// the default behavior.
989 ///
990 /// # Example
991 ///
992 /// ```rust
993 /// use fancy_regex::{RegexOptionsBuilder, seek_pattern_is_useful};
994 ///
995 /// // Use the default filter (equivalent to seek(true))
996 /// let mut builder = RegexOptionsBuilder::new();
997 /// builder.seek_filter(seek_pattern_is_useful);
998 ///
999 /// // Use a custom filter that additionally requires the pattern to be longer than 3 bytes
1000 /// let mut builder = RegexOptionsBuilder::new();
1001 /// builder.seek_filter(|pat| pat.len() > 3 && seek_pattern_is_useful(pat));
1002 /// ```
1003 pub fn seek_filter(&mut self, filter: fn(&str) -> bool) -> &mut Self {
1004 self.options.seek_filter = Some(filter);
1005 self
1006 }
1007
1008 /// Attempts to better match [Oniguruma](https://github.com/kkos/oniguruma)'s default parsing behavior
1009 ///
1010 /// Currently this amounts to changing behavior with:
1011 ///
1012 /// # Left and right word bounds
1013 ///
1014 /// `fancy-regex` follows the default of other regex engines such as the `regex` crate itself
1015 /// where `\<` and `\>` correspond to a _left_ and _right_ word-bound respectively. This
1016 /// differs from Oniguruma's defaults which treat them as matching the literals `<` and `>`.
1017 /// When this option is set using `\<` and `\>` in the pattern will match the literals
1018 /// `<` and `>` instead of word bounds.
1019 ///
1020 /// # Repetition/Quantifiers on empty groups
1021 ///
1022 /// `fancy-regex` would normally reject patterns like `(?:)+` because the `+` has nothing
1023 /// to target. In Oniguruma mode, the empty repeat is silently dropped at parse time.
1024 ///
1025 /// # Swapped order quantifiers
1026 ///
1027 /// `fancy-regex` would normally treat `x{3,0}` as a syntax error because the minimum is
1028 /// greater than the maximum. In Oniguruma mode, the limits are swapped (behaving as
1029 /// `x{0,3}`) and the resulting repeat is treated as atomic (possessive), matching
1030 /// Oniguruma's behavior. A `?` after it is another quantifier rather than a lazy
1031 /// modifier, so `x{3,0}?` is equivalent to `(?:x{3,0})?`.
1032 ///
1033 /// # Adjacent quantifiers
1034 ///
1035 /// `fancy-regex` would normally reject adjacent quantifiers like `a{3}{2}`, treating the
1036 /// second as having nothing to target. In Oniguruma mode, each quantifier wraps the
1037 /// previous result (e.g. `a{3}{2}` becomes `(?:a{3}){2}`).
1038 ///
1039 /// Outside Oniguruma mode, `+` after `{...}` is a possessive modifier (e.g. `x{2}+` is
1040 /// possessive). In Oniguruma mode, `+` after a user-specified `{...}` repeat is treated
1041 /// as another repeat modifier — `x{2}+` is equivalent to `(?:x{2})+`.
1042 ///
1043 /// The same goes for `?` after a fixed `{n}` repeat: outside Oniguruma mode `x{2}?` is lazy,
1044 /// and in Oniguruma mode it is equivalent to `(?:x{2})?`. `x{2,2}?` is lazy in both modes.
1045 ///
1046 /// # Empty interval
1047 ///
1048 /// `fancy-regex` normally treats `x{,}` as `x{0,}`. Oniguruma requires at least one of
1049 /// the limits, so in Oniguruma mode `{,}` matches the literal text `{,}`. `x{,3}` is
1050 /// `x{0,3}` in both modes.
1051 ///
1052 /// # Start of line (`^`) in multiline mode
1053 ///
1054 /// In multiline mode (`(?m)`), `^` normally matches at the start of the input and after
1055 /// any newline. In Oniguruma mode, it additionally rejects a match at the absolute end of
1056 /// the input when it is preceded by a trailing newline.
1057 /// Inside lookarounds, `^` behaves as a plain line start without the end-of-input rejection.
1058 ///
1059 /// # Control character escapes
1060 ///
1061 /// `\cX` and `\C-X` are normally rejected as invalid escapes. In Oniguruma mode they match
1062 /// the control character for *X*, e.g. `\ca` and `\C-a` match `\x01` and `\c?` matches
1063 /// `\x7F`.
1064 ///
1065 /// ## Example
1066 ///
1067 /// ```
1068 /// use fancy_regex::{Regex, RegexBuilder};
1069 ///
1070 /// let haystack = "turbo::<Fish>";
1071 /// let regex = r"\<\w*\>";
1072 ///
1073 /// // By default `\<` and `\>` will match the start and end of a word boundary
1074 /// let word_bounds_regex = Regex::new(regex).unwrap();
1075 /// let word_bounds = word_bounds_regex.find(haystack).unwrap().unwrap();
1076 /// assert_eq!(word_bounds.as_str(), "turbo");
1077 ///
1078 /// // With the option set they instead match the literal `<` and `>` characters
1079 /// let literals_regex = RegexBuilder::new(regex).oniguruma_mode(true).build().unwrap();
1080 /// let literals = literals_regex.find(haystack).unwrap().unwrap();
1081 /// assert_eq!(literals.as_str(), "<Fish>");
1082 /// ```
1083 pub fn oniguruma_mode(&mut self, yes: bool) -> &mut Self {
1084 self.options.oniguruma_mode = yes;
1085 self
1086 }
1087
1088 /// Set the input encoding mode for the regex.
1089 ///
1090 /// Controls how the regex engine handles input encoding. See [`BytesMode`]
1091 /// for details on each variant.
1092 ///
1093 /// Default is [`BytesMode::Unicode`].
1094 ///
1095 /// # Example
1096 ///
1097 /// ```rust
1098 /// use fancy_regex::{BytesMode, RegexBuilder};
1099 ///
1100 /// // ASCII bytes mode: . matches any byte including non-UTF-8
1101 /// let re = RegexBuilder::new(r".+")
1102 /// .bytes_mode(BytesMode::Ascii)
1103 /// .build()
1104 /// .unwrap();
1105 /// assert!(re.is_match(b"\x80\x81\x82").unwrap());
1106 ///
1107 /// // Default Unicode mode: . only matches valid UTF-8 codepoints
1108 /// let re = RegexBuilder::new(r".+")
1109 /// .build()
1110 /// .unwrap();
1111 /// assert!(!re.is_match(b"\x80\x81\x82").unwrap());
1112 /// ```
1113 pub fn bytes_mode(&mut self, mode: BytesMode) -> &mut Self {
1114 self.options.bytes_mode = mode;
1115 self
1116 }
1117
1118 /// Sometimes you want to pass in a haystack containing a trailing newline,
1119 /// and have that last position ignored for the purposes of anchors like ^ and $
1120 /// and even for lookarounds, unless \z is specifically used to anchor to the end of the string.
1121 /// This is how Oniguruma works for example.
1122 pub fn disallow_empty_match_at_eof_after_newline(&mut self, yes: bool) -> &mut Self {
1123 self.options
1124 .hard_regex_runtime_options
1125 .disallow_empty_match_at_eof_after_newline = yes;
1126 self
1127 }
1128
1129 /// Allow [`RegexInput`] assertion suppression overrides at runtime.
1130 ///
1131 /// When enabled, patterns containing `\A` and `\z` are treated as hard and compiled to the VM
1132 /// so that [`RegexInput::start_text`] and [`RegexInput::end_text`] can suppress those
1133 /// assertions.
1134 ///
1135 /// When disabled (the default), those runtime overrides are ignored.
1136 pub fn allow_input_assertion_overrides(&mut self, yes: bool) -> &mut Self {
1137 self.options
1138 .hard_regex_runtime_options
1139 .allow_input_assertion_overrides = yes;
1140 self
1141 }
1142
1143 /// Whether to build a prefilter for this Regex.
1144 /// If you only do anchored search, the prefilter would not be used and would just waste
1145 /// time and memory to build it.
1146 pub fn build_delegate_prefilter(&mut self, yes: bool) -> &mut Self {
1147 self.options.delegate_prefilter = yes;
1148 self
1149 }
1150
1151 /// Computes the bytes a match of `pattern` can start with, without compiling it.
1152 ///
1153 /// The possible return values are:
1154 ///
1155 /// - `Ok(Some(set))`: a byte set could be built and you can quickly check whether a byte
1156 /// could match the pattern without calling the regex
1157 /// - `Ok(None)`: we couldn't built a byte set from the pattern so any byte could match
1158 /// - `Err(..)`: the pattern is invalid
1159 ///
1160 /// This is useful if you are building your own prefilter.
1161 ///
1162 /// The pattern is parsed and then run through the same expression-tree
1163 /// optimization pass that [`Regex::new`](Regex::new) applies before
1164 /// compiling (see [`RegexOptionsBuilder::optimize`](Self::optimize)), so the
1165 /// returned set reflects the tree that would actually be compiled — for
1166 /// example, a trailing positive lookahead is hoisted out before the start
1167 /// bytes are computed. When optimization is disabled, the parsed tree is
1168 /// analyzed as-is.
1169 ///
1170 /// ```
1171 /// # use fancy_regex::RegexOptionsBuilder;
1172 /// let builder = RegexOptionsBuilder::new();
1173 /// let set = builder.start_bytes(r"fn|let|impl").unwrap().unwrap();
1174 /// assert_eq!(set.iter().collect::<Vec<_>>(), vec![b'f', b'i', b'l']);
1175 /// assert!(builder.start_bytes(r"a?").unwrap().is_none());
1176 /// ```
1177 pub fn start_bytes(&self, pattern: &str) -> Result<Option<ByteSet>> {
1178 crate::byte_set::start_bytes(pattern, &self.options)
1179 }
1180
1181 /// Returns the [ByteSet] for the required bytes of the given pattern.
1182 /// For example, a pattern `a?b` will unconditionally require `b` to be found in the
1183 /// haystack. This means that for a haystack like `aaa` the pattern will _never_ match and
1184 /// we can know that without even compiling the regex.
1185 /// An empty set means there's nothing actionable.
1186 ///
1187 /// As with [`start_bytes`](Self::start_bytes), the pattern is parsed and run
1188 /// through the same expression-tree optimization pass that
1189 /// [`Regex::new`](Regex::new) applies before compiling, so the returned set
1190 /// reflects the tree that would actually be compiled. When optimization is
1191 /// disabled, the parsed tree is analyzed as-is.
1192 ///
1193 /// ```
1194 /// # use fancy_regex::RegexOptionsBuilder;
1195 /// let builder = RegexOptionsBuilder::new();
1196 /// let set = builder.required_bytes(r"a?b").unwrap();
1197 /// assert_eq!(set.iter().collect::<Vec<_>>(), vec![b'b']);
1198 /// ```
1199 pub fn required_bytes(&self, pattern: &str) -> Result<ByteSet> {
1200 crate::byte_set::required_bytes(pattern, &self.options)
1201 }
1202}
1203
1204impl RegexBuilder {
1205 /// Create a new regex builder.
1206 pub fn new(pattern: &str) -> Self {
1207 RegexBuilder {
1208 pattern: pattern.to_string(),
1209 options: RegexOptionsBuilder::new(),
1210 }
1211 }
1212
1213 /// Build a `Regex` from the given pattern.
1214 ///
1215 /// Returns an [`Error`](enum.Error.html) if the pattern could not be parsed.
1216 pub fn build(&self) -> Result<Regex> {
1217 self.options.build(self.pattern.clone())
1218 }
1219
1220 /// Change the pattern to build. Useful when building multiple regexes from
1221 /// many patterns.
1222 pub fn pattern(&mut self, pattern: String) -> &mut Self {
1223 self.pattern = pattern;
1224 self
1225 }
1226
1227 /// See [`RegexOptionsBuilder::case_insensitive`]
1228 pub fn case_insensitive(&mut self, yes: bool) -> &mut Self {
1229 self.options.case_insensitive(yes);
1230 self
1231 }
1232
1233 /// See [`RegexOptionsBuilder::multi_line`]
1234 pub fn multi_line(&mut self, yes: bool) -> &mut Self {
1235 self.options.multi_line(yes);
1236 self
1237 }
1238
1239 /// See [`RegexOptionsBuilder::ignore_whitespace`]
1240 pub fn ignore_whitespace(&mut self, yes: bool) -> &mut Self {
1241 self.options.ignore_whitespace(yes);
1242 self
1243 }
1244
1245 /// See [`RegexOptionsBuilder::dot_matches_new_line`]
1246 pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut Self {
1247 self.options.dot_matches_new_line(yes);
1248 self
1249 }
1250
1251 /// See [`RegexOptionsBuilder::verbose_mode`]
1252 pub fn verbose_mode(&mut self, yes: bool) -> &mut Self {
1253 self.options.ignore_whitespace(yes);
1254 self
1255 }
1256
1257 /// See [`RegexOptionsBuilder::unicode_mode`]
1258 pub fn unicode_mode(&mut self, yes: bool) -> &mut Self {
1259 self.options.unicode_mode(yes);
1260 self
1261 }
1262
1263 /// See [`RegexOptionsBuilder::backtrack_limit`]
1264 pub fn backtrack_limit(&mut self, limit: usize) -> &mut Self {
1265 self.options.backtrack_limit(limit);
1266 self
1267 }
1268
1269 /// See [`RegexOptionsBuilder::delegate_size_limit`]
1270 pub fn delegate_size_limit(&mut self, limit: usize) -> &mut Self {
1271 self.options.delegate_size_limit(limit);
1272 self
1273 }
1274
1275 /// See [`RegexOptionsBuilder::delegate_dfa_size_limit`]
1276 pub fn delegate_dfa_size_limit(&mut self, limit: usize) -> &mut Self {
1277 self.options.delegate_dfa_size_limit(limit);
1278 self
1279 }
1280
1281 /// See [`RegexOptionsBuilder::delegate_dfa_skip_cache_capacity_check`]
1282 pub fn delegate_dfa_skip_cache_capacity_check(&mut self, yes: bool) -> &mut Self {
1283 self.options.delegate_dfa_skip_cache_capacity_check(yes);
1284 self
1285 }
1286
1287 /// See [`RegexOptionsBuilder::max_prog_size`]
1288 pub fn max_prog_size(&mut self, limit: usize) -> &mut Self {
1289 self.options.max_prog_size(limit);
1290 self
1291 }
1292
1293 /// See [`RegexOptionsBuilder::oniguruma_mode`]
1294 pub fn oniguruma_mode(&mut self, yes: bool) -> &mut Self {
1295 self.options.oniguruma_mode(yes);
1296 self
1297 }
1298
1299 /// See [`RegexOptionsBuilder::bytes_mode`]
1300 pub fn bytes_mode(&mut self, mode: BytesMode) -> &mut Self {
1301 self.options.bytes_mode(mode);
1302 self
1303 }
1304
1305 /// See [`RegexOptionsBuilder::crlf`]
1306 pub fn crlf(&mut self, yes: bool) -> &mut Self {
1307 self.options.crlf(yes);
1308 self
1309 }
1310
1311 /// See [`RegexOptionsBuilder::find_not_empty`]
1312 pub fn find_not_empty(&mut self, yes: bool) -> &mut Self {
1313 self.options.find_not_empty(yes);
1314 self
1315 }
1316
1317 /// See [`RegexOptionsBuilder::optimize`]
1318 pub fn optimize(&mut self, yes: bool) -> &mut Self {
1319 self.options.optimize(yes);
1320 self
1321 }
1322
1323 /// See [`RegexOptionsBuilder::leftmost_longest`]
1324 #[cfg(feature = "leftmost_longest")]
1325 pub fn leftmost_longest(&mut self, yes: bool) -> &mut Self {
1326 self.options.leftmost_longest(yes);
1327 self
1328 }
1329
1330 /// See [`RegexOptionsBuilder::ignore_numbered_groups_when_named_groups_exist`]
1331 pub fn ignore_numbered_groups_when_named_groups_exist(&mut self, yes: bool) -> &mut Self {
1332 self.options
1333 .ignore_numbered_groups_when_named_groups_exist(yes);
1334 self
1335 }
1336
1337 /// See [`RegexOptionsBuilder::seek`]
1338 pub fn seek(&mut self, yes: bool) -> &mut Self {
1339 self.options.seek(yes);
1340 self
1341 }
1342
1343 /// See [`RegexOptionsBuilder::seek_filter`]
1344 pub fn seek_filter(&mut self, filter: fn(&str) -> bool) -> &mut Self {
1345 self.options.seek_filter(filter);
1346 self
1347 }
1348
1349 /// See [`RegexOptionsBuilder::disallow_empty_match_at_eof_after_newline`]
1350 pub fn disallow_empty_match_at_eof_after_newline(&mut self, yes: bool) -> &mut Self {
1351 self.options.disallow_empty_match_at_eof_after_newline(yes);
1352 self
1353 }
1354
1355 /// See [`RegexOptionsBuilder::allow_input_assertion_overrides`]
1356 pub fn allow_input_assertion_overrides(&mut self, yes: bool) -> &mut Self {
1357 self.options.allow_input_assertion_overrides(yes);
1358 self
1359 }
1360}
1361
1362impl fmt::Debug for Regex {
1363 /// Shows the original regular expression.
1364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1365 write!(f, "{}", self.as_str())
1366 }
1367}
1368
1369impl fmt::Display for Regex {
1370 /// Shows the original regular expression
1371 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1372 write!(f, "{}", self.as_str())
1373 }
1374}
1375
1376impl FromStr for Regex {
1377 type Err = Error;
1378
1379 /// Attempts to parse a string into a regular expression
1380 fn from_str(s: &str) -> Result<Regex> {
1381 Regex::new(s)
1382 }
1383}
1384
1385impl Regex {
1386 /// Parse and compile a regex with default options, see `RegexBuilder`.
1387 ///
1388 /// Returns an [`Error`](enum.Error.html) if the pattern could not be parsed.
1389 pub fn new(re: &str) -> Result<Regex> {
1390 Self::new_options(re.to_string(), &RegexOptions::default())
1391 }
1392
1393 pub(crate) fn new_options(pattern: String, options: &RegexOptions) -> Result<Regex> {
1394 let mut tree = Expr::parse_tree_with_flags(&pattern, options.compute_flags())?;
1395
1396 let find_not_empty = options.hard_regex_runtime_options.find_not_empty;
1397 let disallow_empty_match_at_eof_after_newline = options
1398 .hard_regex_runtime_options
1399 .disallow_empty_match_at_eof_after_newline;
1400 let allow_input_assertion_overrides = options
1401 .hard_regex_runtime_options
1402 .allow_input_assertion_overrides;
1403 #[cfg(feature = "leftmost_longest")]
1404 let leftmost_longest = options.leftmost_longest;
1405
1406 let requires_capture_group_fixup = if !options.should_optimize() {
1407 // Optimization is disabled, either because the user explicitly asked
1408 // for it (`RegexOptionsBuilder::optimize(false)`) or because
1409 // `find_not_empty` is set — in that case the pattern is always
1410 // compiled via the VM anyway, and having the last instruction of the
1411 // expression not be at the end of capture group 0 ruins the empty
1412 // match checking logic. Compile the tree as-is.
1413 false
1414 } else {
1415 // try to optimize the expression tree so that a hard pattern could become easy
1416 // with a fixup of the capture groups. `find_not_empty` is passed through so
1417 // the KeepOut/trailing-lookahead rewrites (which would make the pattern
1418 // delegatable, and the Wrap path can't reject empty matches) are skipped.
1419 optimize(&mut tree, OptimizeOptions { find_not_empty })
1420 };
1421 let info = analyze(
1422 &tree,
1423 AnalyzeContext {
1424 explicit_capture_group_0: requires_capture_group_fixup,
1425 find_not_empty,
1426 disallow_empty_match_at_eof_after_newline,
1427 allow_input_assertion_overrides,
1428 #[cfg(feature = "leftmost_longest")]
1429 leftmost_longest,
1430 },
1431 )?;
1432
1433 if find_not_empty && info.const_size && info.min_size == 0 {
1434 return Err(CompileError::PatternCanNeverMatch.into());
1435 }
1436
1437 if !info.hard {
1438 // easy case, wrap regex
1439
1440 // we do our own to_str because escapes are different
1441 // The cooked form is the pattern plus some flag-group decoration. It is
1442 // kept even though the engine is normally built from an Hir below,
1443 // because it doubles as the seek pattern for RegexSet membership and
1444 // as debug output.
1445 let mut re_cooked = String::with_capacity(pattern.len() + pattern.len() / 2);
1446 tree.expr.to_str(&mut re_cooked, 0);
1447 let compile_options = CompileOptions {
1448 bytes_mode: options.bytes_mode,
1449 unicode: options.syntaxc.get_unicode()
1450 && !matches!(options.bytes_mode, BytesMode::Ascii),
1451 delegate_size_limit: options.delegate_size_limit,
1452 delegate_dfa_size_limit: options.delegate_dfa_size_limit,
1453 delegate_dfa_skip_cache_capacity_check: options
1454 .delegate_dfa_skip_cache_capacity_check,
1455 // The remaining fields (anchored, contains_subroutines, seek_filter,
1456 // disallow_empty_match_at_eof_after_newline) are irrelevant for a plain
1457 // delegate compile in the easy path and their defaults are correct.
1458 ..CompileOptions::default()
1459 };
1460 // The whole pattern is delegated and searched unanchored, so it keeps
1461 // its prefilter and all capture groups (the user may request captures).
1462 // RegexSet members are the exception: they are only searched anchored,
1463 // so their prefilter build is skipped (see `delegate_prefilter`).
1464 let usage = if options.delegate_prefilter {
1465 compile::DelegateUsage::unanchored()
1466 } else {
1467 compile::DelegateUsage::unanchored_no_prefilter()
1468 };
1469 // Build the engine from an Hir translated directly from the tree, so
1470 // the engine doesn't re-parse the cooked pattern. Fall back to the
1471 // string path for anything the translator doesn't cover.
1472 let utf8 = matches!(compile_options.bytes_mode, BytesMode::Unicode);
1473 let mut hir_ctx = to_hir::HirCtx::new(compile_options.unicode, utf8);
1474 hir_ctx.enable_preserve_zero_rep_captures();
1475 let inner = match to_hir::expr_to_hir(&tree.expr, &mut hir_ctx) {
1476 Some(hir) => compile::compile_inner_from_hir(&hir, &compile_options, usage)?,
1477 None => compile::compile_inner(&re_cooked, &compile_options, usage)?,
1478 };
1479 return Ok(Regex {
1480 inner: RegexImpl::Wrap {
1481 inner,
1482 pattern,
1483 explicit_capture_group_0: requires_capture_group_fixup,
1484 delegated_pattern: re_cooked,
1485 zero_rep_groups: hir_ctx.into_zero_rep_groups(),
1486 },
1487 named_groups: Arc::new(tree.named_groups),
1488 });
1489 }
1490
1491 let prog = compile(
1492 &info,
1493 CompileOptions {
1494 anchored: can_compile_as_anchored(&tree.expr),
1495 contains_subroutines: tree.contains_subroutines,
1496 seek_filter: options.seek_filter,
1497 disallow_empty_match_at_eof_after_newline,
1498 bytes_mode: options.bytes_mode,
1499 unicode: options.syntaxc.get_unicode()
1500 && !matches!(options.bytes_mode, BytesMode::Ascii),
1501 delegate_size_limit: options.delegate_size_limit,
1502 delegate_dfa_size_limit: options.delegate_dfa_size_limit,
1503 delegate_dfa_skip_cache_capacity_check: options
1504 .delegate_dfa_skip_cache_capacity_check,
1505 max_prog_size: options.max_prog_size,
1506 },
1507 )?;
1508 Ok(Regex {
1509 inner: RegexImpl::Fancy {
1510 prog: Arc::new(prog),
1511 n_groups: info.end_group(),
1512 options: options.hard_regex_runtime_options,
1513 pattern,
1514 },
1515 named_groups: Arc::new(tree.named_groups),
1516 })
1517 }
1518
1519 /// Returns the original string of this regex.
1520 pub fn as_str(&self) -> &str {
1521 match &self.inner {
1522 RegexImpl::Wrap { pattern, .. } => pattern,
1523 RegexImpl::Fancy { pattern, .. } => pattern,
1524 }
1525 }
1526
1527 /// Check if the regex matches the input.
1528 ///
1529 /// Accepts any type implementing [`Input`]: `&str`, `&String`, or `&[u8]`.
1530 ///
1531 /// # Example
1532 ///
1533 /// Test if some text contains the same word twice:
1534 ///
1535 /// ```rust
1536 /// # use fancy_regex::Regex;
1537 ///
1538 /// let re = Regex::new(r"(\w+) \1").unwrap();
1539 /// assert!(re.is_match("mirror mirror on the wall").unwrap());
1540 /// ```
1541 ///
1542 /// Match against raw bytes:
1543 ///
1544 /// ```rust
1545 /// # use fancy_regex::{BytesMode, RegexBuilder};
1546 ///
1547 /// let re = RegexBuilder::new(r"\d+")
1548 /// .bytes_mode(BytesMode::Ascii)
1549 /// .build()
1550 /// .unwrap();
1551 /// assert!(re.is_match(b"abc 123").unwrap());
1552 /// ```
1553 pub fn is_match<S: input::Input + ?Sized>(&self, input: &S) -> Result<bool> {
1554 self.is_match_input(RegexInput::new(input))
1555 }
1556
1557 /// Returns true if and only if this regex matches anywhere in the given
1558 /// search input.
1559 pub fn is_match_input<S: input::Input + ?Sized>(
1560 &self,
1561 input: RegexInput<'_, S>,
1562 ) -> Result<bool> {
1563 match &self.inner {
1564 RegexImpl::Wrap { inner, .. } => {
1565 if input.is_done() {
1566 Ok(false)
1567 } else {
1568 Ok(inner.is_match(ra_input(&input)))
1569 }
1570 }
1571 RegexImpl::Fancy { .. } => self.find_input_raw(&input, 0).map(|m| m.is_some()),
1572 }
1573 }
1574
1575 /// Returns an iterator for each successive non-overlapping match in `text`.
1576 ///
1577 /// If you have capturing groups in your regex that you want to extract, use the [Regex::captures_iter()]
1578 /// method.
1579 ///
1580 /// # Example
1581 ///
1582 /// Find all words followed by an exclamation point:
1583 ///
1584 /// ```rust
1585 /// # use fancy_regex::Regex;
1586 ///
1587 /// let re = Regex::new(r"\w+(?=!)").unwrap();
1588 /// let mut matches = re.find_iter("so fancy! even with! iterators!");
1589 /// assert_eq!(matches.next().unwrap().unwrap().as_str(), "fancy");
1590 /// assert_eq!(matches.next().unwrap().unwrap().as_str(), "with");
1591 /// assert_eq!(matches.next().unwrap().unwrap().as_str(), "iterators");
1592 /// assert!(matches.next().is_none());
1593 /// ```
1594 pub fn find_iter<'r, 't, S: input::Input + ?Sized>(
1595 &'r self,
1596 text: &'t S,
1597 ) -> Matches<'r, 't, S> {
1598 self.find_iter_input(RegexInput::new(text))
1599 }
1600
1601 /// Returns an iterator for each successive non-overlapping match in the
1602 /// given search input.
1603 pub fn find_iter_input<'r, 't, S: input::Input + ?Sized>(
1604 &'r self,
1605 input: RegexInput<'t, S>,
1606 ) -> Matches<'r, 't, S> {
1607 Matches {
1608 re: self,
1609 input,
1610 last_match: None,
1611 last_skipped_empty: false,
1612 }
1613 }
1614
1615 /// Find the first match in the input.
1616 ///
1617 /// Accepts any type implementing [`Input`]: `&str`, `&String`, or `&[u8]`.
1618 ///
1619 /// # Example
1620 ///
1621 /// Find a word that is followed by an exclamation point:
1622 ///
1623 /// ```rust
1624 /// # use fancy_regex::Regex;
1625 ///
1626 /// let re = Regex::new(r"\w+(?=!)").unwrap();
1627 /// assert_eq!(re.find("so fancy!").unwrap().unwrap().as_str(), "fancy");
1628 /// ```
1629 pub fn find<'t, S: input::Input + ?Sized>(&self, input: &'t S) -> Result<Option<S::Match<'t>>> {
1630 self.find_input(RegexInput::new(input))
1631 }
1632
1633 /// Find the first match in the given search input.
1634 pub fn find_input<'t, S: input::Input + ?Sized>(
1635 &self,
1636 input: RegexInput<'t, S>,
1637 ) -> Result<Option<S::Match<'t>>> {
1638 Ok(self
1639 .find_input_raw(&input, 0)?
1640 .map(|(s, e)| input.haystack().make_match(s, e)))
1641 }
1642
1643 /// Returns the first match in `input`, starting from the specified byte position `pos`.
1644 ///
1645 /// # Examples
1646 ///
1647 /// Finding match starting at a position:
1648 ///
1649 /// ```
1650 /// # use fancy_regex::Regex;
1651 /// let re = Regex::new(r"(?m:^)(\d+)").unwrap();
1652 /// let text = "1 test 123\n2 foo";
1653 /// let mat = re.find_from_pos(text, 7).unwrap().unwrap();
1654 ///
1655 /// assert_eq!(mat.start(), 11);
1656 /// assert_eq!(mat.end(), 12);
1657 /// ```
1658 ///
1659 /// Note that in some cases this is not the same as using the `find`
1660 /// method and passing a slice of the string, see [Regex::captures_from_pos()]
1661 /// for details. To constrain matching to a byte range without slicing, use
1662 /// [Regex::find_input()] with [`RegexInput`].
1663 pub fn find_from_pos<'t, S: input::Input + ?Sized>(
1664 &self,
1665 input: &'t S,
1666 pos: usize,
1667 ) -> Result<Option<S::Match<'t>>> {
1668 self.find_input(RegexInput::new(input).from_pos(pos))
1669 }
1670
1671 pub(crate) fn find_input_raw<S: input::Input + ?Sized>(
1672 &self,
1673 input: &RegexInput<'_, S>,
1674 option_flags: u32,
1675 ) -> Result<Option<(usize, usize)>> {
1676 if input.is_done() {
1677 return Ok(None);
1678 }
1679 match &self.inner {
1680 RegexImpl::Wrap {
1681 inner,
1682 explicit_capture_group_0,
1683 ..
1684 } => {
1685 let mut delegated_input = ra_input(input);
1686 if input.is_anchored() {
1687 delegated_input = delegated_input.anchored(RaAnchored::Yes);
1688 }
1689 let result = if !*explicit_capture_group_0 {
1690 inner.search(&delegated_input).map(|m| (m.start(), m.end()))
1691 } else {
1692 // Only group 1's span is needed (the real match bounds of
1693 // the rewritten pattern); a fixed 4-slot search avoids
1694 // allocating full captures on every find.
1695 let mut slots = [None; 4];
1696 if inner.search_slots(&delegated_input, &mut slots).is_some() {
1697 slots[2]
1698 .zip(slots[3])
1699 .map(|(start, end)| (start.get(), end.get()))
1700 } else {
1701 None
1702 }
1703 };
1704 Ok(result)
1705 }
1706 RegexImpl::Fancy { prog, options, .. } => {
1707 #[allow(unused_mut)]
1708 let mut option_flags = option_flags
1709 | if options.find_not_empty {
1710 OPTION_FIND_NOT_EMPTY
1711 } else {
1712 0
1713 };
1714 #[cfg(feature = "leftmost_longest")]
1715 {
1716 option_flags |= if options.leftmost_longest {
1717 OPTION_LEFTMOST_LONGEST
1718 } else {
1719 0
1720 };
1721 }
1722 // Span-only VM entry: nothing is moved out of the pooled
1723 // scratch, so this path is allocation-free per call.
1724 vm::run_spans(prog, input, option_flags, options)
1725 }
1726 }
1727 }
1728
1729 /// Build a `Captures` value containing only group 0 for the given span.
1730 ///
1731 /// This is used by `RegexSet` as a fast path for patterns without capture
1732 /// groups, where we only need to preserve the overall match range.
1733 ///
1734 /// The caller must pass a valid `start..end` match span for `input`.
1735 /// Behavior is otherwise undefined for APIs reading the resulting captures.
1736 pub(crate) fn captures_for_span<'t, S: input::Input + ?Sized>(
1737 &self,
1738 input: &'t S,
1739 start: usize,
1740 end: usize,
1741 ) -> Captures<'t, S> {
1742 Captures {
1743 inner: CapturesImpl::Fancy {
1744 saves: vec![start, end],
1745 },
1746 named_groups: self.named_groups.clone(),
1747 input,
1748 }
1749 }
1750
1751 /// Returns an iterator over all the non-overlapping capture groups matched in `text`.
1752 ///
1753 /// # Examples
1754 ///
1755 /// Finding all matches and capturing parts of each:
1756 ///
1757 /// ```rust
1758 /// # use fancy_regex::Regex;
1759 ///
1760 /// let re = Regex::new(r"(\d{4})-(\d{2})").unwrap();
1761 /// let text = "It was between 2018-04 and 2020-01";
1762 /// let mut all_captures = re.captures_iter(text);
1763 ///
1764 /// let first = all_captures.next().unwrap().unwrap();
1765 /// assert_eq!(first.get(1).unwrap().as_str(), "2018");
1766 /// assert_eq!(first.get(2).unwrap().as_str(), "04");
1767 /// assert_eq!(first.get(0).unwrap().as_str(), "2018-04");
1768 ///
1769 /// let second = all_captures.next().unwrap().unwrap();
1770 /// assert_eq!(second.get(1).unwrap().as_str(), "2020");
1771 /// assert_eq!(second.get(2).unwrap().as_str(), "01");
1772 /// assert_eq!(second.get(0).unwrap().as_str(), "2020-01");
1773 ///
1774 /// assert!(all_captures.next().is_none());
1775 /// ```
1776 pub fn captures_iter<'r, 't, S: input::Input + ?Sized>(
1777 &'r self,
1778 text: &'t S,
1779 ) -> CaptureMatches<'r, 't, S> {
1780 self.captures_iter_input(RegexInput::new(text))
1781 }
1782
1783 /// Returns an iterator over all the non-overlapping capture groups matched
1784 /// in the given search input.
1785 pub fn captures_iter_input<'r, 't, S: input::Input + ?Sized>(
1786 &'r self,
1787 input: RegexInput<'t, S>,
1788 ) -> CaptureMatches<'r, 't, S> {
1789 CaptureMatches(self.find_iter_input(input))
1790 }
1791
1792 /// Returns the capture groups for the first match in `text`.
1793 ///
1794 /// If no match is found, then `Ok(None)` is returned.
1795 ///
1796 /// # Examples
1797 ///
1798 /// Finding matches and capturing parts of the match:
1799 ///
1800 /// ```rust
1801 /// # use fancy_regex::Regex;
1802 ///
1803 /// let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
1804 /// let text = "The date was 2018-04-07";
1805 /// let captures = re.captures(text).unwrap().unwrap();
1806 ///
1807 /// assert_eq!(captures.get(1).unwrap().as_str(), "2018");
1808 /// assert_eq!(captures.get(2).unwrap().as_str(), "04");
1809 /// assert_eq!(captures.get(3).unwrap().as_str(), "07");
1810 /// assert_eq!(captures.get(0).unwrap().as_str(), "2018-04-07");
1811 /// ```
1812 pub fn captures<'t, S: input::Input + ?Sized>(
1813 &self,
1814 text: &'t S,
1815 ) -> Result<Option<Captures<'t, S>>> {
1816 self.captures_input(RegexInput::new(text))
1817 }
1818
1819 /// Returns the capture groups for the first match in the given search
1820 /// input.
1821 pub fn captures_input<'t, S: input::Input + ?Sized>(
1822 &self,
1823 input: RegexInput<'t, S>,
1824 ) -> Result<Option<Captures<'t, S>>> {
1825 self.captures_input_with_option_flags(&input, 0)
1826 }
1827
1828 /// Returns the capture groups for the first match in `text`, starting from
1829 /// the specified byte position `pos`.
1830 ///
1831 /// # Examples
1832 ///
1833 /// Finding captures starting at a position:
1834 ///
1835 /// ```
1836 /// # use fancy_regex::Regex;
1837 /// let re = Regex::new(r"(?m:^)(\d+)").unwrap();
1838 /// let text = "1 test 123\n2 foo";
1839 /// let captures = re.captures_from_pos(text, 7).unwrap().unwrap();
1840 ///
1841 /// let group = captures.get(1).unwrap();
1842 /// assert_eq!(group.as_str(), "2");
1843 /// assert_eq!(group.start(), 11);
1844 /// assert_eq!(group.end(), 12);
1845 /// ```
1846 ///
1847 /// Note that in some cases this is not the same as using the `captures`
1848 /// method and passing a slice of the string, see the capture that we get
1849 /// when we do this:
1850 ///
1851 /// ```
1852 /// # use fancy_regex::Regex;
1853 /// let re = Regex::new(r"(?m:^)(\d+)").unwrap();
1854 /// let text = "1 test 123\n2 foo";
1855 /// let captures = re.captures(&text[7..]).unwrap().unwrap();
1856 /// assert_eq!(captures.get(1).unwrap().as_str(), "123");
1857 /// ```
1858 ///
1859 /// This matched the number "123" because it's at the beginning of the text
1860 /// of the string slice.
1861 ///
1862 /// To constrain matching to a byte range without slicing, use
1863 /// [Regex::captures_input()] with [`RegexInput`].
1864 ///
1865 pub fn captures_from_pos<'t, S: input::Input + ?Sized>(
1866 &self,
1867 text: &'t S,
1868 pos: usize,
1869 ) -> Result<Option<Captures<'t, S>>> {
1870 self.captures_input(RegexInput::new(text).from_pos(pos))
1871 }
1872
1873 pub(crate) fn captures_input_with_option_flags<'t, S: input::Input + ?Sized>(
1874 &self,
1875 input: &RegexInput<'t, S>,
1876 option_flags: u32,
1877 ) -> Result<Option<Captures<'t, S>>> {
1878 if input.is_done() {
1879 return Ok(None);
1880 }
1881 let named_groups = self.named_groups.clone();
1882 let haystack = input.haystack();
1883 match &self.inner {
1884 RegexImpl::Wrap {
1885 inner,
1886 explicit_capture_group_0,
1887 zero_rep_groups,
1888 ..
1889 } => {
1890 // find_not_empty patterns are always compiled as Fancy, so find_not_empty is
1891 // always false here.
1892 let explicit = *explicit_capture_group_0;
1893 let zero_rep_groups = zero_rep_groups.clone();
1894 let mut locations = inner.create_captures();
1895 let mut delegated_input = ra_input(input);
1896 if input.is_anchored() {
1897 delegated_input = delegated_input.anchored(RaAnchored::Yes);
1898 }
1899 inner.captures(delegated_input, &mut locations);
1900 Ok(locations.is_match().then_some(Captures {
1901 inner: CapturesImpl::Wrap {
1902 locations,
1903 explicit_capture_group_0: explicit,
1904 zero_rep_groups,
1905 },
1906 named_groups,
1907 input: haystack,
1908 }))
1909 }
1910 RegexImpl::Fancy {
1911 prog,
1912 n_groups,
1913 options,
1914 ..
1915 } => {
1916 #[allow(unused_mut)]
1917 let mut option_flags = option_flags
1918 | if options.find_not_empty {
1919 OPTION_FIND_NOT_EMPTY
1920 } else {
1921 0
1922 };
1923 #[cfg(feature = "leftmost_longest")]
1924 {
1925 option_flags |= if options.leftmost_longest {
1926 OPTION_LEFTMOST_LONGEST
1927 } else {
1928 0
1929 };
1930 }
1931 let result = vm::run(prog, input, option_flags, options)?;
1932 Ok(result.map(|mut saves| {
1933 saves.truncate(n_groups * 2);
1934 Captures {
1935 inner: CapturesImpl::Fancy { saves },
1936 named_groups,
1937 input: haystack,
1938 }
1939 }))
1940 }
1941 }
1942 }
1943
1944 pub(crate) fn seek_pattern(&self) -> &str {
1945 match &self.inner {
1946 RegexImpl::Wrap {
1947 delegated_pattern, ..
1948 } => delegated_pattern,
1949 RegexImpl::Fancy { prog, .. } => &prog.seek_pattern,
1950 }
1951 }
1952
1953 /// Returns the number of captures, including the implicit capture of the entire expression.
1954 pub fn captures_len(&self) -> usize {
1955 match &self.inner {
1956 RegexImpl::Wrap {
1957 inner,
1958 explicit_capture_group_0,
1959 ..
1960 } => inner.captures_len() - if *explicit_capture_group_0 { 1 } else { 0 },
1961 RegexImpl::Fancy { n_groups, .. } => *n_groups,
1962 }
1963 }
1964
1965 /// Returns an iterator over the capture names.
1966 pub fn capture_names(&self) -> CaptureNames<'_> {
1967 let mut names = Vec::new();
1968 names.resize(self.captures_len(), None);
1969 for (name, groups) in self.named_groups.iter() {
1970 for &i in groups {
1971 if let Some(slot) = names.get_mut(i) {
1972 *slot = Some(name.as_str());
1973 }
1974 }
1975 }
1976 CaptureNames(names.into_iter())
1977 }
1978
1979 // for debugging only
1980 #[doc(hidden)]
1981 pub fn debug_print(&self, writer: &mut Formatter<'_>) -> fmt::Result {
1982 match &self.inner {
1983 RegexImpl::Wrap {
1984 delegated_pattern,
1985 explicit_capture_group_0,
1986 ..
1987 } => {
1988 write!(
1989 writer,
1990 "wrapped Regex {:?}, explicit_capture_group_0: {:}",
1991 delegated_pattern, *explicit_capture_group_0
1992 )
1993 }
1994 RegexImpl::Fancy { prog, .. } => prog.debug_print(writer),
1995 }
1996 }
1997
1998 /// Replaces the leftmost-first match with the replacement provided.
1999 /// The replacement can be a regular string (where `$N` and `$name` are
2000 /// expanded to match capture groups) or a function that takes the matches'
2001 /// `Captures` and returns the replaced string.
2002 ///
2003 /// If no match is found, then a copy of the string is returned unchanged.
2004 ///
2005 /// # Replacement string syntax
2006 ///
2007 /// All instances of `$name` in the replacement text is replaced with the
2008 /// corresponding capture group `name`.
2009 ///
2010 /// `name` may be an integer corresponding to the index of the
2011 /// capture group (counted by order of opening parenthesis where `0` is the
2012 /// entire match) or it can be a name (consisting of letters, digits or
2013 /// underscores) corresponding to a named capture group.
2014 ///
2015 /// If `name` isn't a valid capture group (whether the name doesn't exist
2016 /// or isn't a valid index), then it is replaced with the empty string.
2017 ///
2018 /// The longest possible name is used. e.g., `$1a` looks up the capture
2019 /// group named `1a` and not the capture group at index `1`. To exert more
2020 /// precise control over the name, use braces, e.g., `${1}a`.
2021 ///
2022 /// To write a literal `$` use `$$`.
2023 ///
2024 /// # Examples
2025 ///
2026 /// Note that this function is polymorphic with respect to the replacement.
2027 /// In typical usage, this can just be a normal string:
2028 ///
2029 /// ```rust
2030 /// # use fancy_regex::Regex;
2031 /// let re = Regex::new("[^01]+").unwrap();
2032 /// assert_eq!(re.replace("1078910", ""), "1010");
2033 /// ```
2034 ///
2035 /// But anything satisfying the `Replacer` trait will work. For example,
2036 /// a closure of type `|&Captures| -> String` provides direct access to the
2037 /// captures corresponding to a match. This allows one to access
2038 /// capturing group matches easily:
2039 ///
2040 /// ```rust
2041 /// # use fancy_regex::{Regex, Captures};
2042 /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap();
2043 /// let result = re.replace("Springsteen, Bruce", |caps: &Captures<'_, str>| {
2044 /// format!("{} {}", &caps[2], &caps[1])
2045 /// });
2046 /// assert_eq!(result, "Bruce Springsteen");
2047 /// ```
2048 ///
2049 /// But this is a bit cumbersome to use all the time. Instead, a simple
2050 /// syntax is supported that expands `$name` into the corresponding capture
2051 /// group. Here's the last example, but using this expansion technique
2052 /// with named capture groups:
2053 ///
2054 /// ```rust
2055 /// # use fancy_regex::Regex;
2056 /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap();
2057 /// let result = re.replace("Springsteen, Bruce", "$first $last");
2058 /// assert_eq!(result, "Bruce Springsteen");
2059 /// ```
2060 ///
2061 /// Note that using `$2` instead of `$first` or `$1` instead of `$last`
2062 /// would produce the same result. To write a literal `$` use `$$`.
2063 ///
2064 /// Sometimes the replacement string requires use of curly braces to
2065 /// delineate a capture group replacement and surrounding literal text.
2066 /// For example, if we wanted to join two words together with an
2067 /// underscore:
2068 ///
2069 /// ```rust
2070 /// # use fancy_regex::Regex;
2071 /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap();
2072 /// let result = re.replace("deep fried", "${first}_$second");
2073 /// assert_eq!(result, "deep_fried");
2074 /// ```
2075 ///
2076 /// Without the curly braces, the capture group name `first_` would be
2077 /// used, and since it doesn't exist, it would be replaced with the empty
2078 /// string.
2079 ///
2080 /// Finally, sometimes you just want to replace a literal string with no
2081 /// regard for capturing group expansion. This can be done by wrapping a
2082 /// byte string with `NoExpand`:
2083 ///
2084 /// ```rust
2085 /// # use fancy_regex::Regex;
2086 /// use fancy_regex::NoExpand;
2087 ///
2088 /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap();
2089 /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last"));
2090 /// assert_eq!(result, "$2 $last");
2091 /// ```
2092 pub fn replace<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Cow<'t, str> {
2093 self.replacen(text, 1, rep)
2094 }
2095
2096 /// Replaces all non-overlapping matches in `text` with the replacement
2097 /// provided. This is the same as calling `replacen` with `limit` set to
2098 /// `0`.
2099 ///
2100 /// See the documentation for `replace` for details on how to access
2101 /// capturing group matches in the replacement string.
2102 pub fn replace_all<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Cow<'t, str> {
2103 self.replacen(text, 0, rep)
2104 }
2105
2106 /// Replaces at most `limit` non-overlapping matches in `text` with the
2107 /// replacement provided. If `limit` is 0, then all non-overlapping matches
2108 /// are replaced.
2109 ///
2110 /// Will panic if any errors are encountered. Use `try_replacen`, which this
2111 /// function unwraps, if you want to handle errors.
2112 ///
2113 /// See the documentation for `replace` for details on how to access
2114 /// capturing group matches in the replacement string.
2115 ///
2116 pub fn replacen<'t, R: Replacer>(&self, text: &'t str, limit: usize, rep: R) -> Cow<'t, str> {
2117 self.try_replacen(text, limit, rep).unwrap()
2118 }
2119
2120 /// Replaces at most `limit` non-overlapping matches in `text` with the
2121 /// replacement provided. If `limit` is 0, then all non-overlapping matches
2122 /// are replaced.
2123 ///
2124 /// Propagates any errors encountered, such as `RuntimeError::BacktrackLimitExceeded`.
2125 ///
2126 /// See the documentation for `replace` for details on how to access
2127 /// capturing group matches in the replacement string.
2128 pub fn try_replacen<'t, R: Replacer>(
2129 &self,
2130 text: &'t str,
2131 limit: usize,
2132 mut rep: R,
2133 ) -> Result<Cow<'t, str>> {
2134 // If we know that the replacement doesn't have any capture expansions,
2135 // then we can fast path. The fast path can make a tremendous
2136 // difference:
2137 //
2138 // 1) We use `find_iter` instead of `captures_iter`. Not asking for
2139 // captures generally makes the regex engines faster.
2140 // 2) We don't need to look up all of the capture groups and do
2141 // replacements inside the replacement string. We just push it
2142 // at each match and be done with it.
2143 if let Some(rep) = rep.no_expansion() {
2144 let mut it = self.find_iter(text).enumerate().peekable();
2145 if it.peek().is_none() {
2146 return Ok(Cow::Borrowed(text));
2147 }
2148 let mut new = String::with_capacity(text.len());
2149 let mut last_match = 0;
2150 for (i, m) in it {
2151 let m = m?;
2152
2153 if limit > 0 && i >= limit {
2154 break;
2155 }
2156 new.push_str(&text[last_match..m.start()]);
2157 new.push_str(&rep);
2158 last_match = m.end();
2159 }
2160 new.push_str(&text[last_match..]);
2161 return Ok(Cow::Owned(new));
2162 }
2163
2164 // The slower path, which we use if the replacement needs access to
2165 // capture groups.
2166 let mut it = self.captures_iter(text).enumerate().peekable();
2167 if it.peek().is_none() {
2168 return Ok(Cow::Borrowed(text));
2169 }
2170 let mut new = String::with_capacity(text.len());
2171 let mut last_match = 0;
2172 for (i, cap) in it {
2173 let cap = cap?;
2174
2175 if limit > 0 && i >= limit {
2176 break;
2177 }
2178 // unwrap on 0 is OK because captures only reports matches
2179 let m = cap.get(0).unwrap();
2180 new.push_str(&text[last_match..m.start()]);
2181 rep.replace_append(&cap, &mut new);
2182 last_match = m.end();
2183 }
2184 new.push_str(&text[last_match..]);
2185 Ok(Cow::Owned(new))
2186 }
2187
2188 /// Splits the string by matches of the regex.
2189 ///
2190 /// Returns an iterator over the substrings of the target string
2191 /// that *aren't* matched by the regex.
2192 ///
2193 /// # Example
2194 ///
2195 /// To split a string delimited by arbitrary amounts of spaces or tabs:
2196 ///
2197 /// ```rust
2198 /// # use fancy_regex::Regex;
2199 /// let re = Regex::new(r"[ \t]+").unwrap();
2200 /// let target = "a b \t c\td e";
2201 /// let fields: Vec<&str> = re.split(target).map(|x| x.unwrap()).collect();
2202 /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]);
2203 /// ```
2204 pub fn split<'r, 'h>(&'r self, target: &'h str) -> Split<'r, 'h> {
2205 Split {
2206 matches: self.find_iter(target),
2207 next_start: 0,
2208 target,
2209 }
2210 }
2211
2212 /// Splits the string by matches of the regex at most `limit` times.
2213 ///
2214 /// Returns an iterator over the substrings of the target string
2215 /// that *aren't* matched by the regex.
2216 ///
2217 /// The `N`th substring is the remaining part of the target.
2218 ///
2219 /// # Example
2220 ///
2221 /// To split a string delimited by arbitrary amounts of spaces or tabs
2222 /// 3 times:
2223 ///
2224 /// ```rust
2225 /// # use fancy_regex::Regex;
2226 /// let re = Regex::new(r"[ \t]+").unwrap();
2227 /// let target = "a b \t c\td e";
2228 /// let fields: Vec<&str> = re.splitn(target, 3).map(|x| x.unwrap()).collect();
2229 /// assert_eq!(fields, vec!["a", "b", "c\td e"]);
2230 /// ```
2231 pub fn splitn<'r, 'h>(&'r self, target: &'h str, limit: usize) -> SplitN<'r, 'h> {
2232 SplitN {
2233 splits: self.split(target),
2234 limit,
2235 }
2236 }
2237}
2238
2239/// `Display` adapter that prints a [`Regex`]'s internal representation via
2240/// [`Regex::debug_print`]. Intended for debugging and test output only.
2241#[doc(hidden)]
2242#[derive(Debug)]
2243#[allow(dead_code)]
2244pub struct DebugRegex<'a>(pub &'a Regex);
2245
2246impl fmt::Display for DebugRegex<'_> {
2247 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2248 self.0.debug_print(f)
2249 }
2250}
2251
2252fn ra_input<'a, S: input::Input + ?Sized>(input: &'a RegexInput<'a, S>) -> RaInput<'a> {
2253 let mut ra_input = RaInput::new(input.haystack().as_bytes()).range(input.get_range());
2254 ra_input.set_start(input.effective_start());
2255 ra_input
2256}
2257
2258impl TryFrom<&str> for Regex {
2259 type Error = Error;
2260
2261 /// Attempts to parse a string into a regular expression
2262 fn try_from(s: &str) -> Result<Self> {
2263 Self::new(s)
2264 }
2265}
2266
2267impl TryFrom<String> for Regex {
2268 type Error = Error;
2269
2270 /// Attempts to parse a string into a regular expression
2271 fn try_from(s: String) -> Result<Self> {
2272 Self::new(&s)
2273 }
2274}
2275
2276impl<'t> Match<'t> {
2277 /// Returns the starting byte offset of the match in the text.
2278 #[inline]
2279 pub fn start(&self) -> usize {
2280 self.start
2281 }
2282
2283 /// Returns the ending byte offset of the match in the text.
2284 #[inline]
2285 pub fn end(&self) -> usize {
2286 self.end
2287 }
2288
2289 /// Returns the range over the starting and ending byte offsets of the match in text.
2290 #[inline]
2291 pub fn range(&self) -> Range<usize> {
2292 self.start..self.end
2293 }
2294
2295 /// Returns the matched text.
2296 #[inline]
2297 pub fn as_str(&self) -> &'t str {
2298 &self.text[self.start..self.end]
2299 }
2300
2301 /// Creates a new match from the given text and byte offsets.
2302 pub(crate) fn new(text: &'t str, start: usize, end: usize) -> Match<'t> {
2303 Match { text, start, end }
2304 }
2305}
2306
2307impl<'t> From<Match<'t>> for &'t str {
2308 fn from(m: Match<'t>) -> &'t str {
2309 m.as_str()
2310 }
2311}
2312
2313impl<'t> From<Match<'t>> for Range<usize> {
2314 fn from(m: Match<'t>) -> Range<usize> {
2315 m.range()
2316 }
2317}
2318
2319#[allow(clippy::len_without_is_empty)] // follow regex's API
2320impl<'t, S: input::Input + ?Sized> Captures<'t, S> {
2321 pub(crate) fn get_span(&self, i: usize) -> Option<(usize, usize)> {
2322 self.inner.get_span(i)
2323 }
2324
2325 /// Get the capture group by its index in the regex.
2326 ///
2327 /// If there is no match for that group or the index does not correspond to a group, `None` is
2328 /// returned. The index 0 returns the whole match.
2329 pub fn get(&self, i: usize) -> Option<S::Match<'t>> {
2330 self.inner
2331 .get_span(i)
2332 .map(|(start, end)| self.input.make_match(start, end))
2333 }
2334
2335 /// Returns the match for a named capture group. Returns `None` the capture
2336 /// group did not match or if there is no group with the given name.
2337 pub fn name(&self, name: &str) -> Option<S::Match<'t>> {
2338 self.named_groups
2339 .get(name)
2340 .and_then(|groups| groups.last())
2341 .and_then(|i| self.get(*i))
2342 }
2343
2344 /// Iterate over the captured groups in order in which they appeared in the regex. The first
2345 /// capture corresponds to the whole match.
2346 pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't, S> {
2347 SubCaptureMatches { data: self, i: 0 }
2348 }
2349
2350 /// How many groups were captured. This is always at least 1 because group 0 returns the whole
2351 /// match.
2352 pub fn len(&self) -> usize {
2353 self.inner.len()
2354 }
2355
2356 /// Returns the byte slice of the entire input that was searched.
2357 pub fn input_as_bytes(&self) -> &'t [u8] {
2358 self.input.as_bytes()
2359 }
2360}
2361
2362// str-only methods
2363impl<'t> Captures<'t, str> {
2364 /// Expands all instances of `$group` in `replacement` to the corresponding
2365 /// capture group `name`, and writes them to the `dst` buffer given.
2366 ///
2367 /// `group` may be an integer corresponding to the index of the
2368 /// capture group (counted by order of opening parenthesis where `\0` is the
2369 /// entire match) or it can be a name (consisting of letters, digits or
2370 /// underscores) corresponding to a named capture group.
2371 ///
2372 /// If `group` isn't a valid capture group (whether the name doesn't exist
2373 /// or isn't a valid index), then it is replaced with the empty string.
2374 ///
2375 /// The longest possible name is used. e.g., `$1a` looks up the capture
2376 /// group named `1a` and not the capture group at index `1`. To exert more
2377 /// precise control over the name, use braces, e.g., `${1}a`.
2378 ///
2379 /// To write a literal `$`, use `$$`.
2380 ///
2381 /// For more control over expansion, see [`Expander`].
2382 ///
2383 /// [`Expander`]: expand/struct.Expander.html
2384 pub fn expand(&self, replacement: &str, dst: &mut String) {
2385 Expander::default().append_expansion(dst, replacement, self);
2386 }
2387}
2388
2389/// Get a group by index.
2390///
2391/// `'t` is the lifetime of the matched text.
2392///
2393/// The text can't outlive the `Captures` object if this method is
2394/// used, because of how `Index` is defined (normally `a[i]` is part
2395/// of `a` and can't outlive it); to do that, use `get()` instead.
2396///
2397/// # Panics
2398///
2399/// If there is no group at the given index.
2400impl<'t> Index<usize> for Captures<'t, str> {
2401 type Output = str;
2402
2403 fn index(&self, i: usize) -> &str {
2404 self.get(i)
2405 .map(|m| m.as_str())
2406 .unwrap_or_else(|| panic!("no group at index '{}'", i))
2407 }
2408}
2409
2410/// Get a group by name.
2411///
2412/// `'t` is the lifetime of the matched text and `'i` is the lifetime
2413/// of the group name (the index).
2414///
2415/// The text can't outlive the `Captures` object if this method is
2416/// used, because of how `Index` is defined (normally `a[i]` is part
2417/// of `a` and can't outlive it); to do that, use `name` instead.
2418///
2419/// # Panics
2420///
2421/// If there is no group named by the given value.
2422impl<'t, 'i> Index<&'i str> for Captures<'t, str> {
2423 type Output = str;
2424
2425 fn index<'a>(&'a self, name: &'i str) -> &'a str {
2426 self.name(name)
2427 .map(|m| m.as_str())
2428 .unwrap_or_else(|| panic!("no group named '{}'", name))
2429 }
2430}
2431
2432impl<'c, 't, S: input::Input + ?Sized> Iterator for SubCaptureMatches<'c, 't, S> {
2433 type Item = Option<S::Match<'t>>;
2434
2435 fn next(&mut self) -> Option<Option<S::Match<'t>>> {
2436 if self.i < self.data.len() {
2437 let result = self.data.get(self.i);
2438 self.i += 1;
2439 Some(result)
2440 } else {
2441 None
2442 }
2443 }
2444}
2445
2446// TODO: might be nice to implement ExactSizeIterator etc for SubCaptures
2447
2448/// Regular expression AST. This is public for now but may change.
2449#[derive(Debug, PartialEq, Eq, Clone)]
2450pub enum Expr {
2451 /// An empty expression, e.g. the last branch in `(a|b|)`
2452 Empty,
2453 /// Any character, regex `.`
2454 Any {
2455 /// Whether it also matches newlines or not
2456 newline: bool,
2457 /// Whether CRLF mode is enabled (`\r` also counts as a newline, so dot
2458 /// excludes both `\r` and `\n`)
2459 crlf: bool,
2460 },
2461 /// An assertion
2462 Assertion(Assertion),
2463 /// General newline sequence, `\R`
2464 /// Matches `\r\n` or any single newline character (\n, \v, \f, \r)
2465 /// In Unicode mode, also matches U+0085, U+2028, U+2029
2466 GeneralNewline {
2467 /// Whether Unicode mode is enabled
2468 unicode: bool,
2469 },
2470 /// The string as a literal, e.g. `a`
2471 Literal {
2472 /// The string to match
2473 val: String,
2474 /// Whether match is case-insensitive or not
2475 casei: bool,
2476 },
2477 /// A literal consisting of raw bytes, produced by `\xHH` escapes where
2478 /// the byte value is greater than 0x7F. In Unicode mode these are
2479 /// re-encoded as UTF-8; in bytes modes they match the exact byte sequence.
2480 LiteralBytes {
2481 /// The raw bytes to match
2482 bytes: Vec<u8>,
2483 },
2484 /// Concatenation of multiple expressions, must match in order, e.g. `a.` is a concatenation of
2485 /// the literal `a` and `.` for any character
2486 Concat(Vec<Expr>),
2487 /// Alternative of multiple expressions, one of them must match, e.g. `a|b` is an alternative
2488 /// where either the literal `a` or `b` must match
2489 Alt(Vec<Expr>),
2490 /// Capturing group of expression, e.g. `(a.)` matches `a` and any character and "captures"
2491 /// (remembers) the match
2492 Group(Arc<Expr>),
2493 /// Look-around (e.g. positive/negative look-ahead or look-behind) with an expression, e.g.
2494 /// `(?=a)` means the next character must be `a` (but the match is not consumed)
2495 LookAround(Box<Expr>, LookAround),
2496 /// Repeat of an expression, e.g. `a*` or `a+` or `a{1,3}`
2497 Repeat {
2498 /// The expression that is being repeated
2499 child: Box<Expr>,
2500 /// The minimum number of repetitions
2501 lo: usize,
2502 /// The maximum number of repetitions (or `usize::MAX`)
2503 hi: usize,
2504 /// Greedy means as much as possible is matched, e.g. `.*b` would match all of `abab`.
2505 /// Non-greedy means as little as possible, e.g. `.*?b` would match only `ab` in `abab`.
2506 greedy: bool,
2507 },
2508 /// Delegate a regex to the regex crate. This is used as a simplification so that we don't have
2509 /// to represent all the expressions in the AST, e.g. character classes.
2510 ///
2511 /// **Constraint**: All Delegate expressions must match exactly 1 character. This ensures
2512 /// consistent analysis and compilation behavior. For zero-width or multi-character patterns,
2513 /// use the appropriate Expr variants instead (e.g., Assertion, Repeat, Concat).
2514 Delegate {
2515 /// The regex
2516 inner: String,
2517 /// Whether the matching is case-insensitive or not
2518 casei: bool,
2519 },
2520 /// Back reference to a capture group, e.g. `\1` in `(abc|def)\1` references the captured group
2521 /// and the whole regex matches either `abcabc` or `defdef`.
2522 Backref {
2523 /// The capture group number being referenced
2524 group: usize,
2525 /// Whether the matching is case-insensitive or not
2526 casei: bool,
2527 },
2528 /// Back reference to a capture group at the given specified relative recursion level.
2529 BackrefWithRelativeRecursionLevel {
2530 /// The capture group number being referenced
2531 group: usize,
2532 /// Relative recursion level
2533 relative_level: isize,
2534 /// Whether the matching is case-insensitive or not
2535 casei: bool,
2536 },
2537 /// Atomic non-capturing group, e.g. `(?>ab|a)` in text that contains `ab` will match `ab` and
2538 /// never backtrack and try `a`, even if matching fails after the atomic group.
2539 AtomicGroup(Box<Expr>),
2540 /// Keep matched text so far out of overall match
2541 KeepOut,
2542 /// Anchor to match at the position where the previous match ended
2543 ContinueFromPreviousMatchEnd,
2544 /// Conditional expression based on whether the numbered capture group matched or not.
2545 /// The optional `relative_recursion_level` qualifies which recursion level's capture is
2546 /// tested (Oniguruma `(?(name+N)...)` syntax).
2547 BackrefExistsCondition {
2548 /// The resolved capture group number
2549 group: usize,
2550 /// Optional relative recursion level (e.g. `+0`, `-1`)
2551 relative_recursion_level: Option<isize>,
2552 },
2553 /// If/Then/Else Condition. If there is no Then/Else, these will just be empty expressions.
2554 Conditional {
2555 /// The conditional expression to evaluate
2556 condition: Box<Expr>,
2557 /// What to execute if the condition is true
2558 true_branch: Box<Expr>,
2559 /// What to execute if the condition is false
2560 false_branch: Box<Expr>,
2561 },
2562 /// Subroutine call to the specified group number
2563 SubroutineCall(usize),
2564 /// Backtracking control verb
2565 BacktrackingControlVerb(BacktrackingControlVerb),
2566 /// Match while the given expression is absent from the haystack
2567 Absent(Absent),
2568 /// DEFINE group - defines capture groups for subroutines without matching anything
2569 /// The expressions inside are parsed and assigned group numbers, but no VM instructions
2570 /// are generated for the DEFINE block itself.
2571 DefineGroup {
2572 /// The expressions/groups being defined
2573 definitions: Box<Expr>,
2574 },
2575 /// Abstract Syntax Tree node - will be resolved into an Expr before analysis.
2576 /// Contains the position in the pattern where the node was parsed from
2577 AstNode(AstNode, usize),
2578}
2579
2580/// Target of a backreference or subroutine call
2581#[derive(Debug, PartialEq, Eq, Clone)]
2582pub enum CaptureGroupTarget {
2583 /// Direct numbered reference
2584 ByNumber(usize),
2585
2586 /// Named reference
2587 ByName(String),
2588
2589 /// Relative reference (e.g., -1, -2, etc.)
2590 Relative(isize),
2591}
2592
2593/// Abstract Syntax Tree node - will be resolved into an Expr before analysis
2594#[derive(Debug, PartialEq, Eq, Clone)]
2595pub enum AstNode {
2596 /// Group with optional name - name is only present if explicitly specified in pattern
2597 AstGroup {
2598 /// Optional name of the capture group, present only when explicitly named in the pattern
2599 name: Option<String>,
2600 /// The inner expression of the group
2601 inner: Box<Expr>,
2602 },
2603 /// Backreference
2604 Backref {
2605 /// The target capture group being referenced
2606 target: CaptureGroupTarget,
2607 /// Whether the matching is case-insensitive or not
2608 // TODO: move out of Backref and prefer a Flags AstNode. The resolver can then track the flags and set casei on the resolved Expr accordingly
2609 casei: bool,
2610 /// Optional relative recursion level for the backreference
2611 relative_recursion_level: Option<isize>,
2612 },
2613 /// Subroutine Call
2614 SubroutineCall(CaptureGroupTarget),
2615 /// Backreference exists condition `(?(name)...)` or `(?(1)...)` - unresolved target.
2616 /// The optional `relative_recursion_level` corresponds to the Oniguruma `+N`/`-N` suffix
2617 /// (e.g. `(?(name+0)...)`) which qualifies which recursion level's capture is tested.
2618 BackrefExistsCondition {
2619 /// The target capture group being tested for existence
2620 target: CaptureGroupTarget,
2621 /// Optional relative recursion level qualifier (e.g. `+0`, `-1`)
2622 relative_recursion_level: Option<isize>,
2623 },
2624}
2625
2626/// Type of look-around assertion as used for a look-around expression.
2627#[derive(Debug, PartialEq, Eq, Clone, Copy)]
2628pub enum LookAround {
2629 /// Look-ahead assertion, e.g. `(?=a)`
2630 LookAhead,
2631 /// Negative look-ahead assertion, e.g. `(?!a)`
2632 LookAheadNeg,
2633 /// Look-behind assertion, e.g. `(?<=a)`
2634 LookBehind,
2635 /// Negative look-behind assertion, e.g. `(?<!a)`
2636 LookBehindNeg,
2637}
2638
2639/// Type of absent operator as used for Oniguruma's absent functionality.
2640#[derive(Debug, PartialEq, Eq, Clone)]
2641pub enum Absent {
2642 /// Absent repeater `(?~absent)` - works like `\O*` (match any character including newline, repeated)
2643 /// but is limited by the range that does not include the string match with `absent`.
2644 /// This is a written abbreviation of `(?~|absent|\O*)`.
2645 Repeater(Box<Expr>),
2646 /// Absent expression `(?~|absent|exp)` - works like `exp`, but is limited by the range
2647 /// that does not include the string match with `absent`.
2648 Expression {
2649 /// The expression to avoid matching
2650 absent: Box<Expr>,
2651 /// The expression to match
2652 exp: Box<Expr>,
2653 },
2654 /// Absent stopper `(?~|absent)` - after this operator, haystack range is limited
2655 /// up to the point where `absent` matches.
2656 Stopper(Box<Expr>),
2657 /// Range clear `(?~|)` - clears the effects caused by absent stoppers.
2658 Clear,
2659}
2660
2661/// Type of backtracking control verb which affects how backtracking will behave.
2662/// See <https://www.regular-expressions.info/verb.html>
2663#[derive(Debug, PartialEq, Eq, Clone, Copy)]
2664pub enum BacktrackingControlVerb {
2665 /// Fail this branch immediately
2666 Fail,
2667 /// Treat match so far as successful overall match
2668 Accept,
2669 /// Abort the entire match on failure
2670 Commit,
2671 /// Restart the entire match attempt at the current position
2672 Skip,
2673 /// Prune all backtracking states and restart the entire match attempt at the next position
2674 Prune,
2675}
2676
2677/// An iterator over capture names in a [Regex]. The iterator
2678/// returns the name of each group, or [None] if the group has
2679/// no name. Because capture group 0 cannot have a name, the
2680/// first item returned is always [None].
2681pub struct CaptureNames<'r>(vec::IntoIter<Option<&'r str>>);
2682
2683impl Debug for CaptureNames<'_> {
2684 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2685 f.write_str("<CaptureNames>")
2686 }
2687}
2688
2689impl<'r> Iterator for CaptureNames<'r> {
2690 type Item = Option<&'r str>;
2691
2692 fn next(&mut self) -> Option<Self::Item> {
2693 self.0.next()
2694 }
2695}
2696
2697// silly to write my own, but this is super-fast for the common 1-digit
2698// case.
2699fn push_usize(s: &mut String, x: usize) {
2700 if x >= 10 {
2701 push_usize(s, x / 10);
2702 s.push((b'0' + (x % 10) as u8) as char);
2703 } else {
2704 s.push((b'0' + (x as u8)) as char);
2705 }
2706}
2707
2708/// Emit a repeat quantifier `?`, `*`, `+`, or `{lo,hi}` (optionally non-greedy) into `buf`.
2709///
2710/// This is shared between [`Expr::to_str`] and `build_seek_pattern` in the compiler.
2711pub(crate) fn write_quantifier(buf: &mut String, lo: usize, hi: usize, greedy: bool) {
2712 match (lo, hi) {
2713 (0, 1) => buf.push('?'),
2714 (0, usize::MAX) => buf.push('*'),
2715 (1, usize::MAX) => buf.push('+'),
2716 (lo, hi) => {
2717 buf.push('{');
2718 push_usize(buf, lo);
2719 if lo != hi {
2720 buf.push(',');
2721 if hi != usize::MAX {
2722 push_usize(buf, hi);
2723 }
2724 }
2725 buf.push('}');
2726 }
2727 }
2728 if !greedy {
2729 buf.push('?');
2730 }
2731}
2732
2733fn is_special(c: char) -> bool {
2734 matches!(
2735 c,
2736 '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' | '{' | '}' | '^' | '$' | '#'
2737 )
2738}
2739
2740pub(crate) fn push_quoted(buf: &mut String, s: &str) {
2741 if !s.bytes().any(|b| {
2742 b == b'\\'
2743 || b == b'\n'
2744 || b == b'\t'
2745 || b == b'\r'
2746 || matches!(
2747 b,
2748 b'.' | b'+'
2749 | b'*'
2750 | b'?'
2751 | b'('
2752 | b')'
2753 | b'|'
2754 | b'['
2755 | b']'
2756 | b'{'
2757 | b'}'
2758 | b'^'
2759 | b'$'
2760 | b'#'
2761 )
2762 }) {
2763 buf.push_str(s);
2764 return;
2765 }
2766
2767 for c in s.chars() {
2768 match c {
2769 '\\' => buf.push_str("\\\\"),
2770 '\n' => buf.push_str("\\n"),
2771 '\t' => buf.push_str("\\t"),
2772 '\r' => buf.push_str("\\r"),
2773 _ => {
2774 if is_special(c) {
2775 buf.push('\\');
2776 }
2777 buf.push(c);
2778 }
2779 }
2780 }
2781}
2782
2783/// Escapes special characters in `text` with '\\'. Returns a string which, when interpreted
2784/// as a regex, matches exactly `text`.
2785pub fn escape(text: &str) -> Cow<'_, str> {
2786 // Using bytes() is OK because all special characters are single bytes.
2787 match text.bytes().filter(|&b| is_special(b as char)).count() {
2788 0 => Cow::Borrowed(text),
2789 n => {
2790 // The capacity calculation is exact because '\\' is a single byte.
2791 let mut buf = String::with_capacity(text.len() + n);
2792 push_quoted(&mut buf, text);
2793 Cow::Owned(buf)
2794 }
2795 }
2796}
2797
2798/// Type of assertions
2799#[derive(Debug, PartialEq, Eq, Clone, Copy)]
2800pub enum Assertion {
2801 /// Start of input text
2802 StartText,
2803 /// End of input text
2804 EndText,
2805 /// End of input text, or before any trailing newlines at the end (Oniguruma's `\Z`)
2806 EndTextIgnoreTrailingNewlines {
2807 /// Whether CRLF mode is enabled.
2808 /// If `true`, trailing `\r\n` pairs (in addition to bare `\n`) are also ignored.
2809 crlf: bool,
2810 },
2811 /// Start of a line
2812 StartLine {
2813 /// CRLF mode.
2814 /// If true, this assertion matches at the starting position of the input text, or at the position immediately
2815 /// following either a `\r` or `\n` character, but never after a `\r` when a `\n` follows.
2816 crlf: bool,
2817 },
2818 /// Start of a line in Oniguruma mode.
2819 /// Behaves like [`Assertion::StartLine`], but additionally rejects matches at the end of the input
2820 /// when it is preceded by a newline.
2821 StartLineOniguruma {
2822 /// CRLF mode.
2823 /// If true, this assertion matches at the starting position of the input text, or at the position immediately
2824 /// following either a `\r` or `\n` character, but never after a `\r` when a `\n` follows.
2825 crlf: bool,
2826 },
2827 /// End of a line
2828 EndLine {
2829 /// CRLF mode
2830 /// If true, this assertion matches at the ending position of the input text, or at the position immediately
2831 /// preceding either a `\r` or `\n` character, but never after a `\r` when a `\n` follows.
2832 crlf: bool,
2833 },
2834 /// Left word boundary
2835 LeftWordBoundary,
2836 /// Left word half boundary
2837 LeftWordHalfBoundary,
2838 /// Right word boundary
2839 RightWordBoundary,
2840 /// Right word half boundary
2841 RightWordHalfBoundary,
2842 /// Both word boundaries
2843 WordBoundary,
2844 /// Not word boundary
2845 NotWordBoundary,
2846}
2847
2848impl Assertion {
2849 /// Whether this assertion is const-size and must be considered for
2850 /// delegation. Word boundaries and `\Z` are const-size; everything else
2851 /// (start/end of line/text) is handled by other analysis branches.
2852 pub(crate) fn is_always_hard(&self) -> bool {
2853 use Assertion::*;
2854 matches!(
2855 self,
2856 // these will make regex-automata use PikeVM and are not compabible with certain regex-automata features we use
2857 LeftWordBoundary
2858 | LeftWordHalfBoundary
2859 | RightWordBoundary
2860 | RightWordHalfBoundary
2861 | WordBoundary
2862 | NotWordBoundary
2863 // `\Z` needs custom trailing-newline handling.
2864 | EndTextIgnoreTrailingNewlines { .. }
2865 )
2866 }
2867
2868 /// Whether this assertion forces the containing expression onto the VM.
2869 ///
2870 /// Word boundaries (`\b`, `\B`, `\<`, `\>`) are only hard inside a
2871 /// lookbehind: regex-automata's reverse DFA can't run a variable-length
2872 /// lookbehind, so the whole lookbehind is compiled on the VM. Outside a
2873 /// lookbehind the engine supports word boundaries, so they can be
2874 /// delegated — which is what keeps patterns like `\b(?:foo|bar|baz)\b`
2875 /// a single delegate instead of one branch per alternative. The
2876 /// half-boundary variants (`\<half`, `\>half`) and `\Z` are always hard:
2877 /// regex-automata has no half-boundary look, and `\Z` needs custom
2878 /// trailing-newline handling.
2879 pub(crate) fn is_hard_in_lookbehind(&self, in_lookbehind: bool) -> bool {
2880 use Assertion::*;
2881 match self {
2882 LeftWordHalfBoundary | RightWordHalfBoundary => true,
2883 EndTextIgnoreTrailingNewlines { .. } => true,
2884 LeftWordBoundary | RightWordBoundary | WordBoundary | NotWordBoundary => in_lookbehind,
2885 _ => true,
2886 }
2887 }
2888}
2889
2890/// An iterator over the immediate children of an [`Expr`].
2891///
2892/// This iterator yields references to child expressions but does not recurse into them.
2893#[derive(Debug)]
2894pub enum ExprChildrenIter<'a> {
2895 /// No children (leaf node)
2896 Empty,
2897 /// A single child (Group, LookAround, AtomicGroup, Repeat)
2898 Single(Option<&'a Expr>),
2899 /// Multiple children in a Vec (Concat, Alt)
2900 Vec(alloc::slice::Iter<'a, Expr>),
2901 /// Three children (Conditional)
2902 Triple {
2903 /// First child
2904 first: Option<&'a Expr>,
2905 /// Second child
2906 second: Option<&'a Expr>,
2907 /// Third child
2908 third: Option<&'a Expr>,
2909 },
2910}
2911
2912/// An iterator over the immediate children of an [`Expr`] for mutable access.
2913///
2914/// This iterator yields mutable references to child expressions but does not recurse into them.
2915#[derive(Debug)]
2916pub enum ExprChildrenIterMut<'a> {
2917 /// No children (leaf node)
2918 Empty,
2919 /// A single child (Group, LookAround, AtomicGroup, Repeat)
2920 Single(Option<&'a mut Expr>),
2921 /// Multiple children in a Vec (Concat, Alt)
2922 Vec(alloc::slice::IterMut<'a, Expr>),
2923 /// Three children (Conditional)
2924 Triple {
2925 /// First child
2926 first: Option<&'a mut Expr>,
2927 /// Second child
2928 second: Option<&'a mut Expr>,
2929 /// Third child
2930 third: Option<&'a mut Expr>,
2931 },
2932}
2933
2934impl<'a> Iterator for ExprChildrenIter<'a> {
2935 type Item = &'a Expr;
2936
2937 fn next(&mut self) -> Option<Self::Item> {
2938 match self {
2939 ExprChildrenIter::Empty => None,
2940 ExprChildrenIter::Single(ref mut child) => child.take(),
2941 ExprChildrenIter::Vec(ref mut iter) => iter.next(),
2942 ExprChildrenIter::Triple {
2943 ref mut first,
2944 ref mut second,
2945 ref mut third,
2946 } => first
2947 .take()
2948 .or_else(|| second.take())
2949 .or_else(|| third.take()),
2950 }
2951 }
2952}
2953
2954impl<'a> Iterator for ExprChildrenIterMut<'a> {
2955 type Item = &'a mut Expr;
2956
2957 fn next(&mut self) -> Option<Self::Item> {
2958 match self {
2959 ExprChildrenIterMut::Empty => None,
2960 ExprChildrenIterMut::Single(ref mut child) => child.take(),
2961 ExprChildrenIterMut::Vec(ref mut iter) => iter.next(),
2962 ExprChildrenIterMut::Triple {
2963 ref mut first,
2964 ref mut second,
2965 ref mut third,
2966 } => first
2967 .take()
2968 .or_else(|| second.take())
2969 .or_else(|| third.take()),
2970 }
2971 }
2972}
2973
2974macro_rules! children_iter_match {
2975 ($self:expr, $iter:ident, $vec_method:ident, $single_method:ident, $group_method:ident) => {
2976 match $self {
2977 Expr::Concat(children) | Expr::Alt(children) => $iter::Vec(children.$vec_method()),
2978 Expr::Group(child) => $iter::Single(Some(Arc::$group_method(child))),
2979 Expr::Absent(Absent::Repeater(child))
2980 | Expr::Absent(Absent::Stopper(child))
2981 | Expr::LookAround(child, _)
2982 | Expr::AtomicGroup(child)
2983 | Expr::Repeat { child, .. } => $iter::Single(Some(child.$single_method())),
2984 Expr::Conditional {
2985 condition,
2986 true_branch,
2987 false_branch,
2988 } => $iter::Triple {
2989 first: Some(condition.$single_method()),
2990 second: Some(true_branch.$single_method()),
2991 third: Some(false_branch.$single_method()),
2992 },
2993 Expr::Absent(Absent::Expression { absent, exp }) => $iter::Triple {
2994 first: Some(absent.$single_method()),
2995 second: Some(exp.$single_method()),
2996 third: None,
2997 },
2998 Expr::DefineGroup { definitions } => $iter::Single(Some(definitions.$single_method())),
2999 _ if $self.is_leaf_node() => $iter::Empty,
3000 _ => unimplemented!(),
3001 }
3002 };
3003}
3004impl Expr {
3005 /// Parse the regex and return an expression (AST) and a bit set with the indexes of groups
3006 /// that are referenced by backrefs.
3007 pub fn parse_tree(re: &str) -> Result<ExprTree> {
3008 Expr::parse_tree_with_flags(re, RegexOptions::default().compute_flags())
3009 }
3010
3011 /// Parse the regex and return an expression (AST)
3012 /// Flags should be bit based based on flags
3013 pub fn parse_tree_with_flags(re: &str, flags: u32) -> Result<ExprTree> {
3014 Parser::parse_with_flags(re, flags)
3015 }
3016
3017 /// Returns `true` if this expression is a leaf node (has no children).
3018 ///
3019 /// Leaf nodes include literals, assertions, backreferences, and other atomic expressions.
3020 /// Non-leaf nodes include groups, concatenations, alternations, and repetitions.
3021 pub fn is_leaf_node(&self) -> bool {
3022 matches!(
3023 self,
3024 Expr::Empty
3025 | Expr::Any { .. }
3026 | Expr::Assertion(_)
3027 | Expr::GeneralNewline { .. }
3028 | Expr::Literal { .. }
3029 | Expr::LiteralBytes { .. }
3030 | Expr::Delegate { .. }
3031 | Expr::Backref { .. }
3032 | Expr::BackrefWithRelativeRecursionLevel { .. }
3033 | Expr::KeepOut
3034 | Expr::ContinueFromPreviousMatchEnd
3035 | Expr::BackrefExistsCondition { .. }
3036 | Expr::BacktrackingControlVerb(_)
3037 | Expr::SubroutineCall(_)
3038 | Expr::Absent(Absent::Clear)
3039 // An unresolved AstNode has no separate child Expr to iterate; the resolver
3040 // should have replaced it before analysis, so treat it as a leaf so that
3041 // collection/iteration doesn't panic, and let the analyzer emit the error.
3042 | Expr::AstNode(..),
3043 )
3044 }
3045
3046 /// Returns `true` if any descendant of this expression (not including itself)
3047 /// satisfies the given predicate.
3048 ///
3049 /// This performs a recursive depth-first search using [`children_iter`](Self::children_iter).
3050 pub fn has_descendant(&self, predicate: impl Fn(&Expr) -> bool) -> bool {
3051 fn go(expr: &Expr, predicate: &dyn Fn(&Expr) -> bool) -> bool {
3052 expr.children_iter()
3053 .any(|child| predicate(child) || go(child, predicate))
3054 }
3055 go(self, &predicate)
3056 }
3057
3058 /// Returns `true` if this expression or any of its descendants satisfies the
3059 /// given predicate.
3060 ///
3061 /// This performs a recursive depth-first search using [`children_iter`](Self::children_iter).
3062 pub fn has_descendant_or_self(&self, predicate: impl Fn(&Expr) -> bool) -> bool {
3063 fn go(expr: &Expr, predicate: &dyn Fn(&Expr) -> bool) -> bool {
3064 if predicate(expr) {
3065 return true;
3066 }
3067 expr.children_iter().any(|child| go(child, predicate))
3068 }
3069 go(self, &predicate)
3070 }
3071
3072 /// Returns an iterator over the immediate children of this expression.
3073 ///
3074 /// For leaf nodes, this returns an empty iterator. For non-leaf nodes, it returns
3075 /// references to their immediate children (non-recursive).
3076 pub fn children_iter(&self) -> ExprChildrenIter<'_> {
3077 children_iter_match!(self, ExprChildrenIter, iter, as_ref, as_ref)
3078 }
3079
3080 /// Returns an iterator over the immediate children of this expression for mutable access.
3081 ///
3082 /// For leaf nodes, this returns an empty iterator. For non-leaf nodes, it returns
3083 /// mutable references to their immediate children (non-recursive).
3084 pub fn children_iter_mut(&mut self) -> ExprChildrenIterMut<'_> {
3085 children_iter_match!(self, ExprChildrenIterMut, iter_mut, as_mut, make_mut)
3086 }
3087
3088 /// Convert expression to a regex string in the regex crate's syntax.
3089 ///
3090 /// # Panics
3091 ///
3092 /// Panics for expressions that are hard, i.e. can not be handled by the regex crate.
3093 pub fn to_str(&self, buf: &mut String, precedence: u8) {
3094 match *self {
3095 Expr::Empty => (),
3096 Expr::Any { newline, crlf } => buf.push_str(match (newline, crlf) {
3097 (true, _) => "(?s:.)",
3098 (false, true) => "(?R-s:.)",
3099 (false, false) => ".",
3100 }),
3101 Expr::Literal { ref val, casei } => {
3102 if casei {
3103 buf.push_str("(?i:");
3104 }
3105 push_quoted(buf, val);
3106 if casei {
3107 buf.push(')');
3108 }
3109 }
3110 Expr::Assertion(Assertion::StartText) => buf.push('^'),
3111 Expr::Assertion(Assertion::EndText) => buf.push('$'),
3112 Expr::Assertion(
3113 Assertion::StartLine { crlf: false }
3114 | Assertion::StartLineOniguruma { crlf: false },
3115 ) => buf.push_str("(?m:^)"),
3116 Expr::Assertion(Assertion::EndLine { crlf: false }) => buf.push_str("(?m:$)"),
3117 Expr::Assertion(
3118 Assertion::StartLine { crlf: true } | Assertion::StartLineOniguruma { crlf: true },
3119 ) => buf.push_str("(?Rm:^)"),
3120 Expr::Assertion(Assertion::EndLine { crlf: true }) => buf.push_str("(?Rm:$)"),
3121 Expr::Assertion(Assertion::WordBoundary) => buf.push_str("\\b"),
3122 Expr::Assertion(Assertion::NotWordBoundary) => buf.push_str("\\B"),
3123 Expr::Assertion(Assertion::LeftWordBoundary) => buf.push_str("\\<"),
3124 Expr::Assertion(Assertion::RightWordBoundary) => buf.push_str("\\>"),
3125 Expr::Assertion(Assertion::LeftWordHalfBoundary) => buf.push_str("\\b{start-half}"),
3126 Expr::Assertion(Assertion::RightWordHalfBoundary) => buf.push_str("\\b{end-half}"),
3127 Expr::Concat(ref children) => {
3128 if precedence > 1 {
3129 buf.push_str("(?:");
3130 }
3131 for child in children {
3132 child.to_str(buf, 2);
3133 }
3134 if precedence > 1 {
3135 buf.push(')')
3136 }
3137 }
3138 Expr::Alt(_) => {
3139 if precedence > 0 {
3140 buf.push_str("(?:");
3141 }
3142 let mut children = self.children_iter();
3143 if let Some(first) = children.next() {
3144 first.to_str(buf, 1);
3145 for child in children {
3146 buf.push('|');
3147 child.to_str(buf, 1);
3148 }
3149 }
3150 if precedence > 0 {
3151 buf.push(')');
3152 }
3153 }
3154 Expr::Group(ref child) => {
3155 buf.push('(');
3156 child.to_str(buf, 0);
3157 buf.push(')');
3158 }
3159 Expr::Repeat {
3160 ref child,
3161 lo,
3162 hi,
3163 greedy,
3164 } => {
3165 if precedence > 2 {
3166 buf.push_str("(?:");
3167 }
3168 child.to_str(buf, 3);
3169 write_quantifier(buf, lo, hi, greedy);
3170 if precedence > 2 {
3171 buf.push(')');
3172 }
3173 }
3174 Expr::Delegate {
3175 ref inner, casei, ..
3176 } => {
3177 // at the moment, delegate nodes are just atoms
3178 if casei {
3179 buf.push_str("(?i:");
3180 }
3181 buf.push_str(inner);
3182 if casei {
3183 buf.push(')');
3184 }
3185 }
3186 Expr::DefineGroup { .. } => {
3187 // DEFINE groups match nothing - output empty string for delegation
3188 }
3189 _ => panic!("attempting to format hard expr {:?}", self),
3190 }
3191 }
3192}
3193
3194// precondition: ix > 0
3195fn prev_codepoint_ix(s: &str, mut ix: usize) -> usize {
3196 let bytes = s.as_bytes();
3197 loop {
3198 ix -= 1;
3199 // fancy bit magic for ranges 0..0x80 + 0xc0..
3200 if (bytes[ix] as i8) >= -0x40 {
3201 break;
3202 }
3203 }
3204 ix
3205}
3206
3207fn codepoint_len(b: u8) -> usize {
3208 match b {
3209 b if b < 0x80 => 1,
3210 b if b < 0xe0 => 2,
3211 b if b < 0xf0 => 3,
3212 _ => 4,
3213 }
3214}
3215
3216// If this returns false, then there is no possible backref in the re
3217
3218// Both potential implementations are turned off, because we currently
3219// always need to do a deeper analysis because of 1-character
3220// look-behind. If we could call a find_from_pos method of regex::Regex,
3221// it would make sense to bring this back.
3222/*
3223pub fn detect_possible_backref(re: &str) -> bool {
3224 let mut last = b'\x00';
3225 for b in re.as_bytes() {
3226 if b'0' <= *b && *b <= b'9' && last == b'\\' { return true; }
3227 last = *b;
3228 }
3229 false
3230}
3231
3232pub fn detect_possible_backref(re: &str) -> bool {
3233 let mut bytes = re.as_bytes();
3234 loop {
3235 match memchr::memchr(b'\\', &bytes[..bytes.len() - 1]) {
3236 Some(i) => {
3237 bytes = &bytes[i + 1..];
3238 let c = bytes[0];
3239 if b'0' <= c && c <= b'9' { return true; }
3240 }
3241 None => return false
3242 }
3243 }
3244}
3245*/
3246
3247/// The internal module only exists so that the toy example can access internals for debugging and
3248/// experimenting.
3249#[doc(hidden)]
3250pub mod internal {
3251 pub use crate::analyze::{analyze, can_compile_as_anchored, AnalyzeContext, Info};
3252 pub use crate::compile::{compile, CompileOptions};
3253 pub use crate::optimize::{optimize, OptimizeOptions};
3254 pub use crate::parse_flags::{
3255 FLAG_CASEI, FLAG_CRLF, FLAG_DOTNL, FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
3256 FLAG_IGNORE_SPACE, FLAG_MULTI, FLAG_ONIGURUMA_MODE, FLAG_UNICODE,
3257 };
3258 pub use crate::vm::{run_default, run_trace, Insn, Prog, Seek};
3259}
3260
3261#[cfg(test)]
3262mod tests {
3263 use alloc::borrow::Cow;
3264 use alloc::boxed::Box;
3265 use alloc::string::{String, ToString};
3266 use alloc::sync::Arc;
3267 use alloc::vec::Vec;
3268 use alloc::{format, vec};
3269
3270 use crate::parse::{make_group, make_literal};
3271 use crate::{Absent, Expr, Regex, RegexBuilder, RegexImpl, RegexInput};
3272
3273 //use detect_possible_backref;
3274
3275 // tests for to_str
3276
3277 fn to_str(e: Expr) -> String {
3278 let mut s = String::new();
3279 e.to_str(&mut s, 0);
3280 s
3281 }
3282
3283 #[test]
3284 fn to_str_concat_alt() {
3285 let e = Expr::Concat(vec![
3286 Expr::Alt(vec![make_literal("a"), make_literal("b")]),
3287 make_literal("c"),
3288 ]);
3289 assert_eq!(to_str(e), "(?:a|b)c");
3290 }
3291
3292 #[test]
3293 fn to_str_rep_concat() {
3294 let e = Expr::Repeat {
3295 child: Box::new(Expr::Concat(vec![make_literal("a"), make_literal("b")])),
3296 lo: 2,
3297 hi: 3,
3298 greedy: true,
3299 };
3300 assert_eq!(to_str(e), "(?:ab){2,3}");
3301 }
3302
3303 #[test]
3304 fn to_str_group_alt() {
3305 let e = Expr::Group(Arc::new(Expr::Alt(vec![
3306 make_literal("a"),
3307 make_literal("b"),
3308 ])));
3309 assert_eq!(to_str(e), "(a|b)");
3310 }
3311
3312 #[test]
3313 fn to_str_literal_special_chars() {
3314 assert_eq!(to_str(make_literal("\n")), "\\n");
3315 assert_eq!(to_str(make_literal("\t")), "\\t");
3316 assert_eq!(to_str(make_literal("\r")), "\\r");
3317 assert_eq!(to_str(make_literal("\\")), "\\\\");
3318 assert_eq!(to_str(make_literal(".")), "\\.");
3319 }
3320
3321 #[test]
3322 fn as_str_debug() {
3323 let s = r"(a+)b\1";
3324 let regex = Regex::new(s).unwrap();
3325 assert_eq!(s, regex.as_str());
3326 assert_eq!(s, format!("{:?}", regex));
3327 }
3328
3329 #[test]
3330 fn display() {
3331 let s = r"(a+)b\1";
3332 let regex = Regex::new(s).unwrap();
3333 assert_eq!(s, format!("{}", regex));
3334 }
3335
3336 #[test]
3337 fn from_str() {
3338 let s = r"(a+)b\1";
3339 let regex = s.parse::<Regex>().unwrap();
3340 assert_eq!(regex.as_str(), s);
3341 }
3342
3343 #[test]
3344 fn to_str_repeat() {
3345 fn repeat(lo: usize, hi: usize, greedy: bool) -> Expr {
3346 Expr::Repeat {
3347 child: Box::new(make_literal("a")),
3348 lo,
3349 hi,
3350 greedy,
3351 }
3352 }
3353
3354 assert_eq!(to_str(repeat(2, 2, true)), "a{2}");
3355 assert_eq!(to_str(repeat(2, 2, false)), "a{2}?");
3356 assert_eq!(to_str(repeat(2, 3, true)), "a{2,3}");
3357 assert_eq!(to_str(repeat(2, 3, false)), "a{2,3}?");
3358 assert_eq!(to_str(repeat(2, usize::MAX, true)), "a{2,}");
3359 assert_eq!(to_str(repeat(2, usize::MAX, false)), "a{2,}?");
3360 assert_eq!(to_str(repeat(0, 1, true)), "a?");
3361 assert_eq!(to_str(repeat(0, 1, false)), "a??");
3362 assert_eq!(to_str(repeat(0, usize::MAX, true)), "a*");
3363 assert_eq!(to_str(repeat(0, usize::MAX, false)), "a*?");
3364 assert_eq!(to_str(repeat(1, usize::MAX, true)), "a+");
3365 assert_eq!(to_str(repeat(1, usize::MAX, false)), "a+?");
3366 }
3367
3368 #[test]
3369 fn escape() {
3370 // Check that strings that need no quoting are borrowed, and that non-special punctuation
3371 // is not quoted.
3372 match crate::escape("@foo") {
3373 Cow::Borrowed(s) => assert_eq!(s, "@foo"),
3374 _ => panic!("Value should be borrowed."),
3375 }
3376
3377 // Check typical usage.
3378 assert_eq!(crate::escape("fo*o").into_owned(), "fo\\*o");
3379
3380 // Check that multibyte characters are handled correctly.
3381 assert_eq!(crate::escape("fø*ø").into_owned(), "fø\\*ø");
3382 }
3383
3384 #[test]
3385 fn push_quoted_special_chars() {
3386 fn pq(s: &str) -> String {
3387 let mut buf = String::new();
3388 crate::push_quoted(&mut buf, s);
3389 buf
3390 }
3391 assert_eq!(pq("\n"), "\\n");
3392 assert_eq!(pq("\t"), "\\t");
3393 assert_eq!(pq("\r"), "\\r");
3394 assert_eq!(pq("\\"), "\\\\");
3395 assert_eq!(pq("."), "\\.");
3396 assert_eq!(pq("hello"), "hello");
3397 assert_eq!(pq("a.b"), "a\\.b");
3398 assert_eq!(pq("fø*ø"), "fø\\*ø");
3399 }
3400
3401 #[test]
3402 fn trailing_positive_lookahead_wrap_capture_group_fixup() {
3403 let s = r"a+(?=c)";
3404 let regex = s.parse::<Regex>().unwrap();
3405 assert!(matches!(regex.inner,
3406 RegexImpl::Wrap { explicit_capture_group_0: true, .. }),
3407 "trailing positive lookahead for an otherwise easy pattern should avoid going through the VM");
3408 assert_eq!(s, regex.as_str());
3409 assert_eq!(s, format!("{:?}", regex));
3410 }
3411
3412 #[test]
3413 fn easy_regex() {
3414 let s = r"(a+)b";
3415 let regex = s.parse::<Regex>().unwrap();
3416 assert!(
3417 matches!(regex.inner, RegexImpl::Wrap { explicit_capture_group_0: false, .. }),
3418 "easy pattern should avoid going through the VM, and capture group 0 should be implicit"
3419 );
3420
3421 assert_eq!(s, regex.as_str());
3422 assert_eq!(s, format!("{:?}", regex));
3423 }
3424
3425 #[test]
3426 fn hard_regex() {
3427 let s = r"(a+)(?>c)";
3428 let regex = s.parse::<Regex>().unwrap();
3429 assert!(
3430 matches!(regex.inner, RegexImpl::Fancy { .. }),
3431 "hard regex should be compiled into a VM"
3432 );
3433 assert_eq!(s, regex.as_str());
3434 assert_eq!(s, format!("{:?}", regex));
3435 }
3436
3437 #[cfg(feature = "leftmost_longest")]
3438 #[test]
3439 fn leftmost_longest_alt_compiles_to_fancy() {
3440 let regex = RegexBuilder::new(r"a|ab")
3441 .leftmost_longest(true)
3442 .build()
3443 .unwrap();
3444 assert!(
3445 matches!(regex.inner, RegexImpl::Fancy { .. }),
3446 "alternation with non-const size should compile to VM when leftmost_longest is enabled"
3447 );
3448 }
3449
3450 #[test]
3451 fn start_end_text_assertions_can_stay_wrap_without_override_opt_in() {
3452 let regex = Regex::new(r"\Afoo\z").unwrap();
3453 assert!(
3454 matches!(regex.inner, RegexImpl::Wrap { .. }),
3455 r"\A...\z should stay on the wrap path unless input assertion overrides are enabled"
3456 );
3457 }
3458
3459 #[test]
3460 fn start_end_text_assertions_become_fancy_with_override_opt_in() {
3461 let regex = RegexBuilder::new(r"\Afoo\z")
3462 .allow_input_assertion_overrides(true)
3463 .build()
3464 .unwrap();
3465 assert!(
3466 matches!(regex.inner, RegexImpl::Fancy { .. }),
3467 r"\A...\z should use the VM when input assertion overrides are enabled"
3468 );
3469 }
3470
3471 /*
3472 #[test]
3473 fn detect_backref() {
3474 assert_eq!(detect_possible_backref("a0a1a2"), false);
3475 assert_eq!(detect_possible_backref("a0a1\\a2"), false);
3476 assert_eq!(detect_possible_backref("a0a\\1a2"), true);
3477 assert_eq!(detect_possible_backref("a0a1a2\\"), false);
3478 }
3479 */
3480
3481 #[test]
3482 fn test_is_leaf_node_leaf_nodes() {
3483 // Test all leaf node variants
3484 assert!(Expr::Empty.is_leaf_node());
3485 assert!(Expr::Any {
3486 newline: false,
3487 crlf: false
3488 }
3489 .is_leaf_node());
3490 assert!(Expr::Any {
3491 newline: true,
3492 crlf: false
3493 }
3494 .is_leaf_node());
3495 assert!(Expr::Assertion(crate::Assertion::StartText).is_leaf_node());
3496 assert!(Expr::Literal {
3497 val: "test".to_string(),
3498 casei: false
3499 }
3500 .is_leaf_node());
3501 assert!(Expr::LiteralBytes { bytes: vec![0x80] }.is_leaf_node());
3502 assert!(Expr::Delegate {
3503 inner: "[0-9]".to_string(),
3504 casei: false,
3505 }
3506 .is_leaf_node());
3507 assert!(Expr::Backref {
3508 group: 1,
3509 casei: false
3510 }
3511 .is_leaf_node());
3512 assert!(Expr::BackrefWithRelativeRecursionLevel {
3513 group: 1,
3514 relative_level: -1,
3515 casei: false
3516 }
3517 .is_leaf_node());
3518 assert!(Expr::KeepOut.is_leaf_node());
3519 assert!(Expr::ContinueFromPreviousMatchEnd.is_leaf_node());
3520 assert!(Expr::BackrefExistsCondition {
3521 group: 1,
3522 relative_recursion_level: None
3523 }
3524 .is_leaf_node());
3525 assert!(Expr::BacktrackingControlVerb(crate::BacktrackingControlVerb::Fail).is_leaf_node());
3526 assert!(Expr::SubroutineCall(1).is_leaf_node());
3527
3528 assert!(Expr::Absent(Absent::Clear).is_leaf_node());
3529 }
3530
3531 #[test]
3532 fn test_is_leaf_node_non_leaf_nodes() {
3533 // Test all non-leaf node variants
3534 assert!(!Expr::Concat(vec![make_literal("a")]).is_leaf_node());
3535 assert!(!Expr::Alt(vec![make_literal("a"), make_literal("b")]).is_leaf_node());
3536 assert!(!make_group(make_literal("a")).is_leaf_node());
3537 assert!(
3538 !Expr::LookAround(Box::new(make_literal("a")), crate::LookAround::LookAhead)
3539 .is_leaf_node()
3540 );
3541 assert!(!Expr::Repeat {
3542 child: Box::new(make_literal("a")),
3543 lo: 0,
3544 hi: 1,
3545 greedy: true
3546 }
3547 .is_leaf_node());
3548 assert!(!Expr::AtomicGroup(Box::new(make_literal("a"))).is_leaf_node());
3549 assert!(!Expr::Conditional {
3550 condition: Box::new(Expr::BackrefExistsCondition {
3551 group: 1,
3552 relative_recursion_level: None
3553 }),
3554 true_branch: Box::new(make_literal("a")),
3555 false_branch: Box::new(Expr::Empty)
3556 }
3557 .is_leaf_node());
3558
3559 assert!(!Expr::Absent(Absent::Repeater(Box::new(make_literal("a")))).is_leaf_node());
3560 assert!(!Expr::Absent(Absent::Expression {
3561 absent: Box::new(make_literal("/*")),
3562 exp: Box::new(Expr::Repeat {
3563 child: Box::new(Expr::Any {
3564 newline: true,
3565 crlf: false
3566 }),
3567 lo: 0,
3568 hi: usize::MAX,
3569 greedy: true
3570 })
3571 })
3572 .is_leaf_node());
3573 assert!(!Expr::Absent(Absent::Stopper(Box::new(make_literal("/*")))).is_leaf_node());
3574 }
3575
3576 #[test]
3577 fn test_children_iter_empty() {
3578 // Leaf nodes should return empty iterator
3579 let expr = Expr::Empty;
3580 let mut iter = expr.children_iter();
3581 assert!(iter.next().is_none());
3582
3583 let expr = make_literal("test");
3584 let mut iter = expr.children_iter();
3585 assert!(iter.next().is_none());
3586 }
3587
3588 #[test]
3589 fn test_children_iter_single() {
3590 // Group, LookAround, AtomicGroup, Repeat should return single child
3591 let child = make_literal("a");
3592 let expr = make_group(child.clone());
3593 let children: Vec<_> = expr.children_iter().collect();
3594 assert_eq!(children.len(), 1);
3595
3596 let expr = Expr::Repeat {
3597 child: Box::new(child.clone()),
3598 lo: 0,
3599 hi: 1,
3600 greedy: true,
3601 };
3602 let children: Vec<_> = expr.children_iter().collect();
3603 assert_eq!(children.len(), 1);
3604 }
3605
3606 #[test]
3607 fn test_children_iter_vec() {
3608 // Concat and Alt should return all children
3609 let children_vec = vec![make_literal("a"), make_literal("b"), make_literal("c")];
3610 let expr = Expr::Concat(children_vec.clone());
3611 let children: Vec<_> = expr.children_iter().collect();
3612 assert_eq!(children.len(), 3);
3613
3614 let expr = Expr::Alt(children_vec);
3615 let children: Vec<_> = expr.children_iter().collect();
3616 assert_eq!(children.len(), 3);
3617 }
3618
3619 #[test]
3620 fn test_children_iter_triple() {
3621 // Conditional should return three children
3622 let expr = Expr::Conditional {
3623 condition: Box::new(Expr::BackrefExistsCondition {
3624 group: 1,
3625 relative_recursion_level: None,
3626 }),
3627 true_branch: Box::new(make_literal("a")),
3628 false_branch: Box::new(make_literal("b")),
3629 };
3630 let children: Vec<_> = expr.children_iter().collect();
3631 assert_eq!(children.len(), 3);
3632
3633 // Absent expression should return two children
3634 let expr = Expr::Absent(Absent::Expression {
3635 absent: Box::new(make_literal("/*")),
3636 exp: Box::new(Expr::Repeat {
3637 child: Box::new(Expr::Any {
3638 newline: true,
3639 crlf: false,
3640 }),
3641 lo: 0,
3642 hi: usize::MAX,
3643 greedy: true,
3644 }),
3645 });
3646 let children: Vec<_> = expr.children_iter().collect();
3647 assert_eq!(children.len(), 2);
3648 }
3649
3650 #[test]
3651 fn find_input_raw_honors_anchored_flag_for_wrapped_regex() {
3652 let regex = Regex::new("abc").unwrap();
3653
3654 // Unanchored search finds match at position 1
3655 let input = RegexInput::new("zabc");
3656 assert_eq!(
3657 Some((1, 4)),
3658 regex
3659 .find_input(input)
3660 .unwrap()
3661 .map(|m| (m.start(), m.end()))
3662 );
3663
3664 // Anchored at position 0 returns None (abc doesn't match at pos 0)
3665 let anchored_at_start = RegexInput::new("zabc").anchored(true);
3666 assert!(regex.find_input(anchored_at_start).unwrap().is_none());
3667
3668 // Anchored at position 1 finds match
3669 let anchored_at_match = RegexInput::new("zabc").from_pos(1).anchored(true);
3670 assert_eq!(
3671 regex
3672 .find_input(anchored_at_match)
3673 .unwrap()
3674 .map(|m| (m.start(), m.end())),
3675 Some((1, 4))
3676 );
3677 }
3678}