/
captures.rs
2546 lines (2459 loc) · 98.8 KB
/
captures.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
Provides types for dealing with capturing groups.
Capturing groups refer to sub-patterns of regexes that some regex engines can
report matching offsets for. For example, matching `[a-z]([0-9]+)` against
`a789` would give `a789` as the overall match (for the implicit capturing group
at index `0`) and `789` as the match for the capturing group `([0-9]+)` (an
explicit capturing group at index `1`).
Not all regex engines can report match offsets for capturing groups. Indeed,
to a first approximation, regex engines that can report capturing group offsets
tend to be quite a bit slower than regex engines that can't. This is because
tracking capturing groups at search time usually requires more "power" that
in turn adds overhead.
Other regex implementations might call capturing groups "submatches."
# Overview
The main types in this module are:
* [`Captures`] records the capturing group offsets found during a search. It
provides convenience routines for looking up capturing group offsets by either
index or name.
* [`GroupInfo`] records the mapping between capturing groups and "slots,"
where the latter are how capturing groups are recorded during a regex search.
This also keeps a mapping from capturing group name to index, and capture
group index to name. A `GroupInfo` is used by `Captures` internally to
provide a convenient API. It is unlikely that you'll use a `GroupInfo`
directly, but for example, if you've compiled an Thompson NFA, then you can use
[`thompson::NFA::group_info`](crate::nfa::thompson::NFA::group_info) to get its
underlying `GroupInfo`.
*/
use alloc::{string::String, sync::Arc, vec, vec::Vec};
use crate::util::{
interpolate,
primitives::{
NonMaxUsize, PatternID, PatternIDError, PatternIDIter, SmallIndex,
},
search::{Match, Span},
};
/// The span offsets of capturing groups after a match has been found.
///
/// This type represents the output of regex engines that can report the
/// offsets at which capturing groups matches or "submatches" occur. For
/// example, the [`PikeVM`](crate::nfa::thompson::pikevm::PikeVM). When a match
/// occurs, it will at minimum contain the [`PatternID`] of the pattern that
/// matched. Depending upon how it was constructed, it may also contain the
/// start/end offsets of the entire match of the pattern and the start/end
/// offsets of each capturing group that participated in the match.
///
/// Values of this type are always created for a specific [`GroupInfo`]. It is
/// unspecified behavior to use a `Captures` value in a search with any regex
/// engine that has a different `GroupInfo` than the one the `Captures` were
/// created with.
///
/// # Constructors
///
/// There are three constructors for this type that control what kind of
/// information is available upon a match:
///
/// * [`Captures::all`]: Will store overall pattern match offsets in addition
/// to the offsets of capturing groups that participated in the match.
/// * [`Captures::matches`]: Will store only the overall pattern
/// match offsets. The offsets of capturing groups (even ones that participated
/// in the match) are not available.
/// * [`Captures::empty`]: Will only store the pattern ID that matched. No
/// match offsets are available at all.
///
/// If you aren't sure which to choose, then pick the first one. The first one
/// is what convenience routines like,
/// [`PikeVM::create_captures`](crate::nfa::thompson::pikevm::PikeVM::create_captures),
/// will use automatically.
///
/// The main difference between these choices is performance. Namely, if you
/// ask for _less_ information, then the execution of regex search may be able
/// to run more quickly.
///
/// # Notes
///
/// It is worth pointing out that this type is not coupled to any one specific
/// regex engine. Instead, its coupling is with [`GroupInfo`], which is the
/// thing that is responsible for mapping capturing groups to "slot" offsets.
/// Slot offsets are indices into a single sequence of memory at which matching
/// haystack offsets for the corresponding group are written by regex engines.
///
/// # Example
///
/// This example shows how to parse a simple date and extract the components of
/// the date via capturing groups:
///
/// ```
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
///
/// let re = PikeVM::new(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})$")?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// re.captures(&mut cache, "2010-03-14", &mut caps);
/// assert!(caps.is_match());
/// assert_eq!(Some(Span::from(0..4)), caps.get_group(1));
/// assert_eq!(Some(Span::from(5..7)), caps.get_group(2));
/// assert_eq!(Some(Span::from(8..10)), caps.get_group(3));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: named capturing groups
///
/// This example is like the one above, but leverages the ability to name
/// capturing groups in order to make the code a bit clearer:
///
/// ```
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
///
/// let re = PikeVM::new(r"^(?P<y>[0-9]{4})-(?P<m>[0-9]{2})-(?P<d>[0-9]{2})$")?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// re.captures(&mut cache, "2010-03-14", &mut caps);
/// assert!(caps.is_match());
/// assert_eq!(Some(Span::from(0..4)), caps.get_group_by_name("y"));
/// assert_eq!(Some(Span::from(5..7)), caps.get_group_by_name("m"));
/// assert_eq!(Some(Span::from(8..10)), caps.get_group_by_name("d"));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone)]
pub struct Captures {
/// The group info that these capture groups are coupled to. This is what
/// gives the "convenience" of the `Captures` API. Namely, it provides the
/// slot mapping and the name|-->index mapping for capture lookups by name.
group_info: GroupInfo,
/// The ID of the pattern that matched. Regex engines must set this to
/// None when no match occurs.
pid: Option<PatternID>,
/// The slot values, i.e., submatch offsets.
///
/// In theory, the smallest sequence of slots would be something like
/// `max(groups(pattern) for pattern in regex) * 2`, but instead, we use
/// `sum(groups(pattern) for pattern in regex) * 2`. Why?
///
/// Well, the former could be used in theory, because we don't generally
/// have any overlapping APIs that involve capturing groups. Therefore,
/// there's technically never any need to have slots set for multiple
/// patterns. However, this might change some day, in which case, we would
/// need to have slots available.
///
/// The other reason is that during the execution of some regex engines,
/// there exists a point in time where multiple slots for different
/// patterns may be written to before knowing which pattern has matched.
/// Therefore, the regex engines themselves, in order to support multiple
/// patterns correctly, must have all slots available. If `Captures`
/// doesn't have all slots available, then regex engines can't write
/// directly into the caller provided `Captures` and must instead write
/// into some other storage and then copy the slots involved in the match
/// at the end of the search.
///
/// So overall, at least as of the time of writing, it seems like the path
/// of least resistance is to just require allocating all possible slots
/// instead of the conceptual minimum. Another way to justify this is that
/// the most common case is a single pattern, in which case, there is no
/// inefficiency here since the 'max' and 'sum' calculations above are
/// equivalent in that case.
///
/// N.B. The mapping from group index to slot is maintained by `GroupInfo`
/// and is considered an API guarantee. See `GroupInfo` for more details on
/// that mapping.
///
/// N.B. `Option<NonMaxUsize>` has the same size as a `usize`.
slots: Vec<Option<NonMaxUsize>>,
}
impl Captures {
/// Create new storage for the offsets of all matching capturing groups.
///
/// This routine provides the most information for matches---namely, the
/// spans of matching capturing groups---but also requires the regex search
/// routines to do the most work.
///
/// It is unspecified behavior to use the returned `Captures` value in a
/// search with a `GroupInfo` other than the one that is provided to this
/// constructor.
///
/// # Example
///
/// This example shows that all capturing groups---but only ones that
/// participated in a match---are available to query after a match has
/// been found:
///
/// ```
/// use regex_automata::{
/// nfa::thompson::pikevm::PikeVM,
/// util::captures::Captures,
/// Span, Match,
/// };
///
/// let re = PikeVM::new(
/// r"^(?:(?P<lower>[a-z]+)|(?P<upper>[A-Z]+))(?P<digits>[0-9]+)$",
/// )?;
/// let mut cache = re.create_cache();
/// let mut caps = Captures::all(re.get_nfa().group_info().clone());
///
/// re.captures(&mut cache, "ABC123", &mut caps);
/// assert!(caps.is_match());
/// assert_eq!(Some(Match::must(0, 0..6)), caps.get_match());
/// // The 'lower' group didn't match, so it won't have any offsets.
/// assert_eq!(None, caps.get_group_by_name("lower"));
/// assert_eq!(Some(Span::from(0..3)), caps.get_group_by_name("upper"));
/// assert_eq!(Some(Span::from(3..6)), caps.get_group_by_name("digits"));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn all(group_info: GroupInfo) -> Captures {
let slots = group_info.slot_len();
Captures { group_info, pid: None, slots: vec![None; slots] }
}
/// Create new storage for only the full match spans of a pattern. This
/// does not include any capturing group offsets.
///
/// It is unspecified behavior to use the returned `Captures` value in a
/// search with a `GroupInfo` other than the one that is provided to this
/// constructor.
///
/// # Example
///
/// This example shows that only overall match offsets are reported when
/// this constructor is used. Accessing any capturing groups other than
/// the 0th will always return `None`.
///
/// ```
/// use regex_automata::{
/// nfa::thompson::pikevm::PikeVM,
/// util::captures::Captures,
/// Match,
/// };
///
/// let re = PikeVM::new(
/// r"^(?:(?P<lower>[a-z]+)|(?P<upper>[A-Z]+))(?P<digits>[0-9]+)$",
/// )?;
/// let mut cache = re.create_cache();
/// let mut caps = Captures::matches(re.get_nfa().group_info().clone());
///
/// re.captures(&mut cache, "ABC123", &mut caps);
/// assert!(caps.is_match());
/// assert_eq!(Some(Match::must(0, 0..6)), caps.get_match());
/// // We didn't ask for capturing group offsets, so they aren't available.
/// assert_eq!(None, caps.get_group_by_name("lower"));
/// assert_eq!(None, caps.get_group_by_name("upper"));
/// assert_eq!(None, caps.get_group_by_name("digits"));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn matches(group_info: GroupInfo) -> Captures {
// This is OK because we know there are at least this many slots,
// and GroupInfo construction guarantees that the number of slots fits
// into a usize.
let slots = group_info.pattern_len().checked_mul(2).unwrap();
Captures { group_info, pid: None, slots: vec![None; slots] }
}
/// Create new storage for only tracking which pattern matched. No offsets
/// are stored at all.
///
/// It is unspecified behavior to use the returned `Captures` value in a
/// search with a `GroupInfo` other than the one that is provided to this
/// constructor.
///
/// # Example
///
/// This example shows that only the pattern that matched can be accessed
/// from a `Captures` value created via this constructor.
///
/// ```
/// use regex_automata::{
/// nfa::thompson::pikevm::PikeVM,
/// util::captures::Captures,
/// PatternID,
/// };
///
/// let re = PikeVM::new_many(&[r"[a-z]+", r"[A-Z]+"])?;
/// let mut cache = re.create_cache();
/// let mut caps = Captures::empty(re.get_nfa().group_info().clone());
///
/// re.captures(&mut cache, "aABCz", &mut caps);
/// assert!(caps.is_match());
/// assert_eq!(Some(PatternID::must(0)), caps.pattern());
/// // We didn't ask for any offsets, so they aren't available.
/// assert_eq!(None, caps.get_match());
///
/// re.captures(&mut cache, &"aABCz"[1..], &mut caps);
/// assert!(caps.is_match());
/// assert_eq!(Some(PatternID::must(1)), caps.pattern());
/// // We didn't ask for any offsets, so they aren't available.
/// assert_eq!(None, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn empty(group_info: GroupInfo) -> Captures {
Captures { group_info, pid: None, slots: vec![] }
}
/// Returns true if and only if this capturing group represents a match.
///
/// This is a convenience routine for `caps.pattern().is_some()`.
///
/// # Example
///
/// When using the PikeVM (for example), the lightest weight way of
/// detecting whether a match exists is to create capturing groups that
/// only track the ID of the pattern that match (if any):
///
/// ```
/// use regex_automata::{
/// nfa::thompson::pikevm::PikeVM,
/// util::captures::Captures,
/// };
///
/// let re = PikeVM::new(r"[a-z]+")?;
/// let mut cache = re.create_cache();
/// let mut caps = Captures::empty(re.get_nfa().group_info().clone());
///
/// re.captures(&mut cache, "aABCz", &mut caps);
/// assert!(caps.is_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn is_match(&self) -> bool {
self.pid.is_some()
}
/// Returns the identifier of the pattern that matched when this
/// capturing group represents a match. If no match was found, then this
/// always returns `None`.
///
/// This returns a pattern ID in precisely the cases in which `is_match`
/// returns `true`. Similarly, the pattern ID returned is always the
/// same pattern ID found in the `Match` returned by `get_match`.
///
/// # Example
///
/// When using the PikeVM (for example), the lightest weight way of
/// detecting which pattern matched is to create capturing groups that only
/// track the ID of the pattern that match (if any):
///
/// ```
/// use regex_automata::{
/// nfa::thompson::pikevm::PikeVM,
/// util::captures::Captures,
/// PatternID,
/// };
///
/// let re = PikeVM::new_many(&[r"[a-z]+", r"[A-Z]+"])?;
/// let mut cache = re.create_cache();
/// let mut caps = Captures::empty(re.get_nfa().group_info().clone());
///
/// re.captures(&mut cache, "ABC", &mut caps);
/// assert_eq!(Some(PatternID::must(1)), caps.pattern());
/// // Recall that offsets are only available when using a non-empty
/// // Captures value. So even though a match occurred, this returns None!
/// assert_eq!(None, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn pattern(&self) -> Option<PatternID> {
self.pid
}
/// Returns the pattern ID and the span of the match, if one occurred.
///
/// This always returns `None` when `Captures` was created with
/// [`Captures::empty`], even if a match was found.
///
/// If this routine returns a non-`None` value, then `is_match` is
/// guaranteed to return `true` and `pattern` is also guaranteed to return
/// a non-`None` value.
///
/// # Example
///
/// This example shows how to get the full match from a search:
///
/// ```
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
///
/// let re = PikeVM::new_many(&[r"[a-z]+", r"[A-Z]+"])?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// re.captures(&mut cache, "ABC", &mut caps);
/// assert_eq!(Some(Match::must(1, 0..3)), caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn get_match(&self) -> Option<Match> {
Some(Match::new(self.pattern()?, self.get_group(0)?))
}
/// Returns the span of a capturing group match corresponding to the group
/// index given, only if both the overall pattern matched and the capturing
/// group participated in that match.
///
/// This returns `None` if `index` is invalid. `index` is valid if and only
/// if it's less than [`Captures::group_len`] for the matching pattern.
///
/// This always returns `None` when `Captures` was created with
/// [`Captures::empty`], even if a match was found. This also always
/// returns `None` for any `index > 0` when `Captures` was created with
/// [`Captures::matches`].
///
/// If this routine returns a non-`None` value, then `is_match` is
/// guaranteed to return `true`, `pattern` is guaranteed to return a
/// non-`None` value and `get_match` is guaranteed to return a non-`None`
/// value.
///
/// By convention, the 0th capture group will always return the same
/// span as the span returned by `get_match`. This is because the 0th
/// capture group always corresponds to the entirety of the pattern's
/// match. (It is similarly always unnamed because it is implicit.) This
/// isn't necessarily true of all regex engines. For example, one can
/// hand-compile a [`thompson::NFA`](crate::nfa::thompson::NFA) via a
/// [`thompson::Builder`](crate::nfa::thompson::Builder), which isn't
/// technically forced to make the 0th capturing group always correspond to
/// the entire match.
///
/// # Example
///
/// This example shows how to get the capturing groups, by index, from a
/// match:
///
/// ```
/// # if cfg!(miri) { return Ok(()); } // miri takes too long
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span, Match};
///
/// let re = PikeVM::new(r"^(?P<first>\pL+)\s+(?P<last>\pL+)$")?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// re.captures(&mut cache, "Bruce Springsteen", &mut caps);
/// assert_eq!(Some(Match::must(0, 0..17)), caps.get_match());
/// assert_eq!(Some(Span::from(0..5)), caps.get_group(1));
/// assert_eq!(Some(Span::from(6..17)), caps.get_group(2));
/// // Looking for a non-existent capturing group will return None:
/// assert_eq!(None, caps.get_group(3));
/// assert_eq!(None, caps.get_group(9944060567225171988));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn get_group(&self, index: usize) -> Option<Span> {
let pid = self.pattern()?;
// There's a little bit of work needed to map captures to slots in the
// fully general case. But in the overwhelming common case of a single
// pattern, we can just do some simple arithmetic.
let (slot_start, slot_end) = if self.group_info().pattern_len() == 1 {
(index.checked_mul(2)?, index.checked_mul(2)?.checked_add(1)?)
} else {
self.group_info().slots(pid, index)?
};
let start = self.slots.get(slot_start).copied()??;
let end = self.slots.get(slot_end).copied()??;
Some(Span { start: start.get(), end: end.get() })
}
/// Returns the span of a capturing group match corresponding to the group
/// name given, only if both the overall pattern matched and the capturing
/// group participated in that match.
///
/// This returns `None` if `name` does not correspond to a valid capturing
/// group for the pattern that matched.
///
/// This always returns `None` when `Captures` was created with
/// [`Captures::empty`], even if a match was found. This also always
/// returns `None` for any `index > 0` when `Captures` was created with
/// [`Captures::matches`].
///
/// If this routine returns a non-`None` value, then `is_match` is
/// guaranteed to return `true`, `pattern` is guaranteed to return a
/// non-`None` value and `get_match` is guaranteed to return a non-`None`
/// value.
///
/// # Example
///
/// This example shows how to get the capturing groups, by name, from a
/// match:
///
/// ```
/// # if cfg!(miri) { return Ok(()); } // miri takes too long
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span, Match};
///
/// let re = PikeVM::new(r"^(?P<first>\pL+)\s+(?P<last>\pL+)$")?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// re.captures(&mut cache, "Bruce Springsteen", &mut caps);
/// assert_eq!(Some(Match::must(0, 0..17)), caps.get_match());
/// assert_eq!(Some(Span::from(0..5)), caps.get_group_by_name("first"));
/// assert_eq!(Some(Span::from(6..17)), caps.get_group_by_name("last"));
/// // Looking for a non-existent capturing group will return None:
/// assert_eq!(None, caps.get_group_by_name("middle"));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn get_group_by_name(&self, name: &str) -> Option<Span> {
let index = self.group_info().to_index(self.pattern()?, name)?;
self.get_group(index)
}
/// Returns an iterator of possible spans for every capturing group in the
/// matching pattern.
///
/// If this `Captures` value does not correspond to a match, then the
/// iterator returned yields no elements.
///
/// Note that the iterator returned yields elements of type `Option<Span>`.
/// A span is present if and only if it corresponds to a capturing group
/// that participated in a match.
///
/// # Example
///
/// This example shows how to collect all capturing groups:
///
/// ```
/// # if cfg!(miri) { return Ok(()); } // miri takes too long
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
///
/// let re = PikeVM::new(
/// // Matches first/last names, with an optional middle name.
/// r"^(?P<first>\pL+)\s+(?:(?P<middle>\pL+)\s+)?(?P<last>\pL+)$",
/// )?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// re.captures(&mut cache, "Harry James Potter", &mut caps);
/// assert!(caps.is_match());
/// let groups: Vec<Option<Span>> = caps.iter().collect();
/// assert_eq!(groups, vec![
/// Some(Span::from(0..18)),
/// Some(Span::from(0..5)),
/// Some(Span::from(6..11)),
/// Some(Span::from(12..18)),
/// ]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// This example uses the same regex as the previous example, but with a
/// haystack that omits the middle name. This results in a capturing group
/// that is present in the elements yielded by the iterator but without a
/// match:
///
/// ```
/// # if cfg!(miri) { return Ok(()); } // miri takes too long
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
///
/// let re = PikeVM::new(
/// // Matches first/last names, with an optional middle name.
/// r"^(?P<first>\pL+)\s+(?:(?P<middle>\pL+)\s+)?(?P<last>\pL+)$",
/// )?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// re.captures(&mut cache, "Harry Potter", &mut caps);
/// assert!(caps.is_match());
/// let groups: Vec<Option<Span>> = caps.iter().collect();
/// assert_eq!(groups, vec![
/// Some(Span::from(0..12)),
/// Some(Span::from(0..5)),
/// None,
/// Some(Span::from(6..12)),
/// ]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn iter(&self) -> CapturesPatternIter<'_> {
let names = self
.pattern()
.map_or(GroupInfoPatternNames::empty().enumerate(), |pid| {
self.group_info().pattern_names(pid).enumerate()
});
CapturesPatternIter { caps: self, names }
}
/// Return the total number of capturing groups for the matching pattern.
///
/// If this `Captures` value does not correspond to a match, then this
/// always returns `0`.
///
/// This always returns the same number of elements yielded by
/// [`Captures::iter`]. That is, the number includes capturing groups even
/// if they don't participate in the match.
///
/// # Example
///
/// This example shows how to count the total number of capturing groups
/// associated with a pattern. Notice that it includes groups that did not
/// participate in a match (just like `Captures::iter` does).
///
/// ```
/// # if cfg!(miri) { return Ok(()); } // miri takes too long
/// use regex_automata::nfa::thompson::pikevm::PikeVM;
///
/// let re = PikeVM::new(
/// // Matches first/last names, with an optional middle name.
/// r"^(?P<first>\pL+)\s+(?:(?P<middle>\pL+)\s+)?(?P<last>\pL+)$",
/// )?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// re.captures(&mut cache, "Harry Potter", &mut caps);
/// assert_eq!(4, caps.group_len());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn group_len(&self) -> usize {
let pid = match self.pattern() {
None => return 0,
Some(pid) => pid,
};
self.group_info().group_len(pid)
}
/// Returns a reference to the underlying group info on which these
/// captures are based.
///
/// The difference between `GroupInfo` and `Captures` is that the former
/// defines the structure of capturing groups where as the latter is what
/// stores the actual match information. So where as `Captures` only gives
/// you access to the current match, `GroupInfo` lets you query any
/// information about all capturing groups, even ones for patterns that
/// weren't involved in a match.
///
/// Note that a `GroupInfo` uses reference counting internally, so it may
/// be cloned cheaply.
///
/// # Example
///
/// This example shows how to get all capturing group names from the
/// underlying `GroupInfo`. Notice that we don't even need to run a
/// search.
///
/// ```
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
///
/// let re = PikeVM::new_many(&[
/// r"(?P<foo>a)",
/// r"(a)(b)",
/// r"ab",
/// r"(?P<bar>a)(?P<quux>a)",
/// r"(?P<foo>z)",
/// ])?;
/// let caps = re.create_captures();
///
/// let expected = vec![
/// (PatternID::must(0), 0, None),
/// (PatternID::must(0), 1, Some("foo")),
/// (PatternID::must(1), 0, None),
/// (PatternID::must(1), 1, None),
/// (PatternID::must(1), 2, None),
/// (PatternID::must(2), 0, None),
/// (PatternID::must(3), 0, None),
/// (PatternID::must(3), 1, Some("bar")),
/// (PatternID::must(3), 2, Some("quux")),
/// (PatternID::must(4), 0, None),
/// (PatternID::must(4), 1, Some("foo")),
/// ];
/// // We could also just use 're.get_nfa().group_info()'.
/// let got: Vec<(PatternID, usize, Option<&str>)> =
/// caps.group_info().all_names().collect();
/// assert_eq!(expected, got);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn group_info(&self) -> &GroupInfo {
&self.group_info
}
/// Interpolates the capture references in `replacement` with the
/// corresponding substrings in `haystack` matched by each reference. The
/// interpolated string is returned.
///
/// See the [`interpolate` module](interpolate) for documentation on the
/// format of the replacement string.
///
/// # Example
///
/// This example shows how to use interpolation, and also shows how it
/// can work with multi-pattern regexes.
///
/// ```
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
///
/// let re = PikeVM::new_many(&[
/// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
/// r"(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
/// ])?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
///
/// let replacement = "year=$year, month=$month, day=$day";
///
/// // This matches the first pattern.
/// let hay = "On 14-03-2010, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// let result = caps.interpolate_string(hay, replacement);
/// assert_eq!("year=2010, month=03, day=14", result);
///
/// // And this matches the second pattern.
/// let hay = "On 2010-03-14, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// let result = caps.interpolate_string(hay, replacement);
/// assert_eq!("year=2010, month=03, day=14", result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn interpolate_string(
&self,
haystack: &str,
replacement: &str,
) -> String {
let mut dst = String::new();
self.interpolate_string_into(haystack, replacement, &mut dst);
dst
}
/// Interpolates the capture references in `replacement` with the
/// corresponding substrings in `haystack` matched by each reference. The
/// interpolated string is written to `dst`.
///
/// See the [`interpolate` module](interpolate) for documentation on the
/// format of the replacement string.
///
/// # Example
///
/// This example shows how to use interpolation, and also shows how it
/// can work with multi-pattern regexes.
///
/// ```
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
///
/// let re = PikeVM::new_many(&[
/// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
/// r"(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
/// ])?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
///
/// let replacement = "year=$year, month=$month, day=$day";
///
/// // This matches the first pattern.
/// let hay = "On 14-03-2010, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// let mut dst = String::new();
/// caps.interpolate_string_into(hay, replacement, &mut dst);
/// assert_eq!("year=2010, month=03, day=14", dst);
///
/// // And this matches the second pattern.
/// let hay = "On 2010-03-14, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// let mut dst = String::new();
/// caps.interpolate_string_into(hay, replacement, &mut dst);
/// assert_eq!("year=2010, month=03, day=14", dst);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn interpolate_string_into(
&self,
haystack: &str,
replacement: &str,
dst: &mut String,
) {
interpolate::string(
replacement,
|index, dst| {
let span = match self.get_group(index) {
None => return,
Some(span) => span,
};
dst.push_str(&haystack[span]);
},
|name| self.group_info().to_index(self.pattern()?, name),
dst,
);
}
/// Interpolates the capture references in `replacement` with the
/// corresponding substrings in `haystack` matched by each reference. The
/// interpolated byte string is returned.
///
/// See the [`interpolate` module](interpolate) for documentation on the
/// format of the replacement string.
///
/// # Example
///
/// This example shows how to use interpolation, and also shows how it
/// can work with multi-pattern regexes.
///
/// ```
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
///
/// let re = PikeVM::new_many(&[
/// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
/// r"(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
/// ])?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
///
/// let replacement = b"year=$year, month=$month, day=$day";
///
/// // This matches the first pattern.
/// let hay = b"On 14-03-2010, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// let result = caps.interpolate_bytes(hay, replacement);
/// assert_eq!(&b"year=2010, month=03, day=14"[..], result);
///
/// // And this matches the second pattern.
/// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// let result = caps.interpolate_bytes(hay, replacement);
/// assert_eq!(&b"year=2010, month=03, day=14"[..], result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn interpolate_bytes(
&self,
haystack: &[u8],
replacement: &[u8],
) -> Vec<u8> {
let mut dst = vec![];
self.interpolate_bytes_into(haystack, replacement, &mut dst);
dst
}
/// Interpolates the capture references in `replacement` with the
/// corresponding substrings in `haystack` matched by each reference. The
/// interpolated byte string is written to `dst`.
///
/// See the [`interpolate` module](interpolate) for documentation on the
/// format of the replacement string.
///
/// # Example
///
/// This example shows how to use interpolation, and also shows how it
/// can work with multi-pattern regexes.
///
/// ```
/// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
///
/// let re = PikeVM::new_many(&[
/// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
/// r"(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
/// ])?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
///
/// let replacement = b"year=$year, month=$month, day=$day";
///
/// // This matches the first pattern.
/// let hay = b"On 14-03-2010, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// let mut dst = vec![];
/// caps.interpolate_bytes_into(hay, replacement, &mut dst);
/// assert_eq!(&b"year=2010, month=03, day=14"[..], dst);
///
/// // And this matches the second pattern.
/// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// let mut dst = vec![];
/// caps.interpolate_bytes_into(hay, replacement, &mut dst);
/// assert_eq!(&b"year=2010, month=03, day=14"[..], dst);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn interpolate_bytes_into(
&self,
haystack: &[u8],
replacement: &[u8],
dst: &mut Vec<u8>,
) {
interpolate::bytes(
replacement,
|index, dst| {
let span = match self.get_group(index) {
None => return,
Some(span) => span,
};
dst.extend_from_slice(&haystack[span]);
},
|name| self.group_info().to_index(self.pattern()?, name),
dst,
);
}
/// This is a convenience routine for extracting the substrings
/// corresponding to matching capture groups in the given `haystack`. The
/// `haystack` should be the same substring used to find the match spans in
/// this `Captures` value.
///
/// This is identical to [`Captures::extract_bytes`], except it works with
/// `&str` instead of `&[u8]`.
///
/// # Panics
///
/// This panics if the number of explicit matching groups in this
/// `Captures` value is less than `N`. This also panics if this `Captures`
/// value does not correspond to a match.
///
/// Note that this does *not* panic if the number of explicit matching
/// groups is bigger than `N`. In that case, only the first `N` matching
/// groups are extracted.
///
/// # Example
///
/// ```
/// use regex_automata::nfa::thompson::pikevm::PikeVM;
///
/// let re = PikeVM::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})")?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
///
/// let hay = "On 2010-03-14, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// assert!(caps.is_match());
/// let (full, [year, month, day]) = caps.extract(hay);
/// assert_eq!("2010-03-14", full);
/// assert_eq!("2010", year);
/// assert_eq!("03", month);
/// assert_eq!("14", day);
///
/// // We can also ask for fewer than all capture groups.
/// let (full, [year]) = caps.extract(hay);
/// assert_eq!("2010-03-14", full);
/// assert_eq!("2010", year);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn extract<'h, const N: usize>(
&self,
haystack: &'h str,
) -> (&'h str, [&'h str; N]) {
let mut matched = self.iter().flatten();
let whole_match = &haystack[matched.next().expect("a match")];
let group_matches = [0; N].map(|_| {
let sp = matched.next().expect("too few matching groups");
&haystack[sp]
});
(whole_match, group_matches)
}
/// This is a convenience routine for extracting the substrings
/// corresponding to matching capture groups in the given `haystack`. The
/// `haystack` should be the same substring used to find the match spans in
/// this `Captures` value.
///
/// This is identical to [`Captures::extract`], except it works with
/// `&[u8]` instead of `&str`.
///
/// # Panics
///
/// This panics if the number of explicit matching groups in this
/// `Captures` value is less than `N`. This also panics if this `Captures`
/// value does not correspond to a match.
///
/// Note that this does *not* panic if the number of explicit matching
/// groups is bigger than `N`. In that case, only the first `N` matching
/// groups are extracted.
///
/// # Example
///
/// ```
/// use regex_automata::nfa::thompson::pikevm::PikeVM;
///
/// let re = PikeVM::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})")?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
///
/// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
/// re.captures(&mut cache, hay, &mut caps);
/// assert!(caps.is_match());
/// let (full, [year, month, day]) = caps.extract_bytes(hay);
/// assert_eq!(b"2010-03-14", full);
/// assert_eq!(b"2010", year);
/// assert_eq!(b"03", month);
/// assert_eq!(b"14", day);
///
/// // We can also ask for fewer than all capture groups.
/// let (full, [year]) = caps.extract_bytes(hay);
/// assert_eq!(b"2010-03-14", full);
/// assert_eq!(b"2010", year);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn extract_bytes<'h, const N: usize>(
&self,
haystack: &'h [u8],
) -> (&'h [u8], [&'h [u8]; N]) {
let mut matched = self.iter().flatten();
let whole_match = &haystack[matched.next().expect("a match")];
let group_matches = [0; N].map(|_| {
let sp = matched.next().expect("too few matching groups");
&haystack[sp]
});