Debian Codegraph @

debian/rust-vendor/fancy-regex/tests/finding.rs

raw
1 mod common;
2
3 use fancy_regex::{BytesMode, Match, RegexBuilder, RegexInput};
4 use matches::assert_matches;
5 use std::ops::Range;
6
7 #[test]
8 fn match_api() {
9 let m = find_match(r"(\w+)", "... test").unwrap();
10 assert_eq!(m.range(), (4..8));
11 assert_eq!(Range::from(m), (4..8));
12 assert_eq!(m.as_str(), "test");
13 }
14
15 #[test]
16 fn find_wrap() {
17 assert_eq!(find(r"(\w+)", "... test"), Some((4, 8)));
18 assert_eq!(find(r"(?m)^yes$", "foo\nyes\n"), Some((4, 7)));
19 }
20
21 #[test]
22 fn find_fancy_case_insensitive() {
23 assert_eq!(find(r"(x|xy)\1", "XX"), None);
24 assert_eq!(find(r"(x|xy)\1", "xx"), Some((0, 2)));
25 assert_eq!(find(r"((?i:x|xy))\1", "XX"), Some((0, 2)));
26 }
27
28 #[test]
29 fn lookahead_grouping_single_expression() {
30 // These would fail if the delegate expression was `^x|a` (if we didn't
31 // group as `^(?:x|a)`).
32 assert_eq!(find(r"(?=x|a)", "a"), Some((0, 0)));
33 assert_eq!(find(r"(?=x|a)", "bbba"), Some((3, 3)));
34 }
35
36 #[test]
37 fn lookahead_grouping_multiple_expressions() {
38 // These would fail if the delegate expression was `^ab|Bc` (if we didn't
39 // preserve grouping of `(?:b|B)`).
40 assert_eq!(find(r"(?=(?!x)a(?:b|B)c)", "aBc"), Some((0, 0)));
41 assert_eq!(find(r"(?=(?!x)a(?:b|B)c)", "Bc"), None);
42 }
43
44 #[test]
45 fn lookbehind_grouping_single_expression() {
46 assert_eq!(find(r"(?<=x|a)", "a"), Some((1, 1)));
47 assert_eq!(find(r"(?<=x|a)", "ba"), Some((2, 2)));
48 assert_eq!(find(r"(?<=^a)", "a"), Some((1, 1)));
49 assert_eq!(find(r"(?<=^a)", "ba"), None);
50 }
51
52 #[test]
53 fn lookbehind_variable_sized_alt() {
54 // These get compiled into multiple alternative lookbehinds
55 assert_eq!(find(r"(?<=a|bc)", "xxa"), Some((3, 3)));
56 assert_eq!(find(r"(?<=a|bc)", "xxbc"), Some((4, 4)));
57 assert_eq!(find(r"(?<=a|bc)", "xx"), None);
58 assert_eq!(find(r"(?<=a|bc)", "xxb"), None);
59 assert_eq!(find(r"(?<=a|bc)", "xxc"), None);
60 }
61
62 #[test]
63 fn negative_lookbehind_variable_sized_alt() {
64 assert_eq!(find(r"(?<!a|bc)x", "axx"), Some((2, 3)));
65 assert_eq!(find(r"(?<!a|bc)x", "bcxx"), Some((3, 4)));
66 assert_eq!(find(r"(?<!a|bc)x", "x"), Some((0, 1)));
67 assert_eq!(find(r"(?<!a|bc)x", "bx"), Some((1, 2)));
68 assert_eq!(find(r"(?<!a|bc)x", "cx"), Some((1, 2)));
69 assert_eq!(find(r"(?<!a|bc)x", "ax"), None);
70 assert_eq!(find(r"(?<!a|bc)x", "bcx"), None);
71 }
72
73 #[test]
74 #[cfg(feature = "variable-lookbehinds")]
75 fn lookbehind_positive_variable_sized_functionality_easy() {
76 assert_eq!(find(r"(?<=a(?:b|cd))x", "abx"), Some((2, 3)));
77 assert_eq!(find(r"(?<=a(?:b|cd))x", "acdx"), Some((3, 4)));
78 assert_eq!(find(r"(?<=a(?:b|cd))x", "ax"), None);
79 assert_eq!(find(r"(?<=a(?:b|cd))x", "bcx"), None);
80
81 assert_eq!(find(r"(?<=a+b+)x", "abx"), Some((2, 3)));
82 assert_eq!(find(r"(?<=a+b+)x", "aabbx"), Some((4, 5)));
83 assert_eq!(find(r"(?<=a+b+)x", "aaabbbx"), Some((6, 7)));
84 assert_eq!(find(r"(?<=a+b+)x", "ax"), None);
85 assert_eq!(find(r"(?<=a+b+)x", "bx"), None);
86 assert_eq!(find(r"(?<=a+b+)x", "abcx"), None);
87 assert_eq!(find(r"(?<=a+b+)c", "bc aabbc"), Some((7, 8)));
88
89 assert_eq!(find(r"\b(?<=\|\s{0,9})(?:[gG]pu)\b", "|gpu"), Some((1, 4)));
90 assert_eq!(
91 find(r"\b(?<=\|\s{0,9})(?:[gG]pu)\b", "| gpu"),
92 Some((3, 6))
93 );
94 }
95
96 #[test]
97 #[cfg(feature = "variable-lookbehinds")]
98 fn lookbehind_negative_variable_sized_functionality_easy() {
99 assert_eq!(find(r"(?<!a(?:b|cd))x", "abx"), None);
100 assert_eq!(find(r"(?<!a(?:b|cd))x", "acdx"), None);
101 assert_eq!(find(r"(?<!a(?:b|cd))x", "ax"), Some((1, 2)));
102 assert_eq!(find(r"(?<!a(?:b|cd))x", "bcx"), Some((2, 3)));
103
104 assert_eq!(find(r"(?<!a+b+)x", "abx"), None);
105 assert_eq!(find(r"(?<!a+b+)x", "aabbx"), None);
106 assert_eq!(find(r"(?<!a+b+)x", "aaabbbx"), None);
107 assert_eq!(find(r"(?<!a+b+)x", "ax"), Some((1, 2)));
108 assert_eq!(find(r"(?<!a+b+)x", "bx"), Some((1, 2)));
109 assert_eq!(find(r"(?<!a+b+)x", "abcx"), Some((3, 4)));
110 assert_eq!(find(r"(?<!a+b+)c", "aabbc bc"), Some((7, 8)));
111
112 assert_eq!(find(r"\b(?<!\|\s{0,9})(?:[gG]pu)\b", "|gpu"), None);
113 assert_eq!(find(r"\b(?<!\|\s{0,9})(?:[gG]pu)\b", "| gpu"), None);
114 }
115
116 #[test]
117 #[cfg(feature = "variable-lookbehinds")]
118 fn lookbehind_with_word_boundary_and_variable_length() {
119 // Test (?<=\ba+)b - word boundary followed by variable-length a's
120 assert_eq!(find(r"(?<=\ba+)b", "aaab"), Some((3, 4)));
121 assert_eq!(find(r"(?<=\ba+)b", " aaab"), Some((4, 5)));
122 assert_eq!(find(r"(?<=\ba+)b", "ab"), Some((1, 2)));
123 assert_eq!(find(r"(?<=\ba+)b", "xaaab"), None); // No word boundary
124 assert_eq!(find(r"(?<=\ba+)b", "b"), None); // No 'a's before 'b'
125
126 // Test (?<=\Ba+)b - NOT word boundary followed by variable-length a's
127 assert_eq!(find(r"(?<=\Ba+)b", "a_aab"), Some((4, 5)));
128
129 // Test negative lookbehind with word boundary
130 assert_eq!(find(r"(?<!\ba+)b", "xaaab"), Some((4, 5))); // 'a's not preceded by word boundary
131 assert_eq!(find(r"(?<!\ba+)b", "aaab"), None); // Word boundary before 'a's
132 assert_eq!(find(r"(?<!\ba+)b", " aaab"), None); // Word boundary after space
133 assert_eq!(find(r"(?<!\ba+)b", "b"), Some((0, 1))); // lookbehind doesn't match
134
135 assert_eq!(
136 find(r"(?=fuly)(?<=\b(?:[A-Z][a-z]*|[a-z]+))fuly\b", "Carefuly"),
137 Some((4, 8))
138 );
139
140 assert_eq!(find(r"(.)b+(?<=\1\1b+)x", "aabbx"), Some((1, 5)));
141 }
142
143 #[test]
144 #[cfg(feature = "variable-lookbehinds")]
145 fn lookbehind_positive_variable_sized_functionality_unicode() {
146 assert_eq!(find_str_only(r"(?<=\b\w+\b)", "ežeras"), Some((7, 7)));
147 assert_eq!(
148 find_str_only(r"(?<=\b\w+[ ]\d)", "ežeras 123"),
149 Some((9, 9))
150 );
151 }
152
153 #[test]
154 fn lookbehind_containing_const_size_backref() {
155 assert_eq!(find(r"(..)(?<=\1\1)", "yyxxxx"), Some((4, 6)));
156 }
157
158 #[test]
159 fn lookahead_looks_left() {
160 assert_eq!(find(r"a(?=\b)", "ab"), None);
161 assert_eq!(find(r"a(?=\b)", "a."), Some((0, 1)));
162 assert_eq!(find(r"a(?=\b|_)", "a."), Some((0, 1)));
163 assert_eq!(find(r"a(?=_|\b)", "a."), Some((0, 1)));
164 }
165
166 #[test]
167 fn negative_lookahead_fail() {
168 // This was a tricky one. There's a negative lookahead that contains a
169 // "hard" alternative (because of the lookahead). When the VM gets to the
170 // point where the body of the negative lookahead matched, it needs to fail
171 // the negative lookahead match. That means it needs to pop the stack until
172 // before the negative lookahead, and then fail. But how many times it has
173 // to pop is not fixed, it depends on the body/VM state.
174 assert_eq!(find(r"(?!a(?=b)|x)", "ab"), Some((1, 1)));
175 assert_eq!(find(r"(?!`(?:[^`]+(?=`)|x)`)", "`a`"), Some((1, 1)));
176 }
177
178 #[test]
179 fn backref_for_unmatched_group() {
180 assert_eq!(find(r"(a)?\1", "bb"), None);
181 }
182
183 #[test]
184 fn backref_with_multibyte() {
185 assert_eq!(
186 find_str_only(r"(.+)\1+", "x\u{1F431}\u{1F436}\u{1F431}\u{1F436}"),
187 Some((1, 17))
188 );
189 }
190
191 #[test]
192 fn case_insensitive_backref_with_non_ascii() {
193 assert_eq!(
194 find_str_only(r"(?i)(?<word>\w+)\s+\k<word>", "Greek : δ Δ"),
195 Some((8, 13))
196 );
197 assert_eq!(
198 find_str_only(r"(?i)(?<word>\w+)\s+\k<word>", "foo 🎯 test bar BaR"),
199 Some((14, 21))
200 );
201 }
202
203 #[test]
204 fn repeat_non_greedy() {
205 // (?=a) to make it fancy and use VM
206 assert_eq!(find(r"(a(?=a)){2,}?", "aaa"), Some((0, 2)));
207 assert_eq!(find(r"(a(?=a)){2}?a", "aaa"), Some((0, 3)));
208 }
209
210 #[test]
211 fn empty_repeat_non_greedy() {
212 // (?=b) to make it fancy and use VM
213 assert_eq!(find(r"(a(?=b)|)+?", "ab"), Some((0, 1)));
214 // This tests the "prevent zero-length match on repeat" logic
215 assert_eq!(find(r"(a(?=b)|)+?x", "ab"), None);
216 }
217
218 #[test]
219 fn any_match_unicode_scalar_value() {
220 assert_eq!(find_str_only(r"(.)\1", "\u{1F60A}\u{1F60A}"), Some((0, 8)));
221 assert_eq!(
222 find_str_only(r"(?s)(.)\1", "\u{1F60A}\u{1F60A}"),
223 Some((0, 8))
224 );
225 }
226
227 #[test]
228 fn delegates_match_unicode_scalar_value() {
229 assert_eq!(find_str_only(r".(?=a)", "\u{1F60A}a"), Some((0, 4)));
230 assert_eq!(find_str_only(r".(?=\ba+)", "\u{1F60A}a"), Some((0, 4)));
231 }
232
233 #[test]
234 fn keepout_matches_in_correct_place() {
235 assert_eq!(find(r"a\Kb", "aaab"), Some((3, 4)));
236 assert_eq!(find(r".+\Kb", "aaab"), Some((3, 4)));
237 assert_eq!(find(r"(?:aaa\K)b", "aaab"), Some((3, 4)));
238 }
239
240 #[test]
241 fn keepout_in_lookarounds_match_in_correct_place() {
242 assert_eq!(find(r"(?<=a\Kb)c", "abc"), Some((1, 3)));
243 assert_eq!(find(r"(?<!a\Kb)c", "axc"), Some((2, 3)));
244 assert_eq!(find(r"a(?=b\Kc)", "abc"), Some((1, 1)));
245 assert_eq!(find(r"a(?=b\Kc)..", "abc"), Some((2, 3)));
246 assert_eq!(find(r"a(?!b\Kc)", "abx"), Some((0, 1)));
247 }
248
249 #[test]
250 fn find_no_matches_when_continuing_from_previous_match_end_and_no_match_at_start_of_text() {
251 assert_eq!(find(r"\G(\d)\d", " 1122 33"), None);
252 }
253
254 #[test]
255 fn find_iter() {
256 let text = "11 22 33";
257
258 for (i, mat) in common::regex(r"(\d)\d").find_iter(text).enumerate() {
259 let mat = mat.unwrap();
260
261 match i {
262 0 => assert_eq!((mat.start(), mat.end()), (0, 2)),
263 1 => assert_eq!((mat.start(), mat.end()), (3, 5)),
264 2 => assert_eq!((mat.start(), mat.end()), (6, 8)),
265 i => panic!("Expected 3 captures, got {}", i + 1),
266 }
267 }
268 }
269
270 #[test]
271 fn find_iter_overlapping_lookahead() {
272 let text = "abcdef";
273
274 for (i, mat) in common::regex(r"[a-z]{2}(?=[a-z])")
275 .find_iter(text)
276 .enumerate()
277 {
278 let mat = mat.unwrap();
279
280 match i {
281 0 => assert_eq!((mat.start(), mat.end()), (0, 2)),
282 1 => assert_eq!((mat.start(), mat.end()), (2, 4)),
283 i => panic!("Expected 2 captures, got {}", i + 1),
284 }
285 }
286 }
287
288 #[test]
289 fn find_iter_zero_length() {
290 let text = "ab1c2";
291
292 for (i, mat) in common::regex(r"\d*(?=[a-z])").find_iter(text).enumerate() {
293 let mat = mat.unwrap();
294
295 match i {
296 0 => assert_eq!((mat.start(), mat.end()), (0, 0)),
297 1 => assert_eq!((mat.start(), mat.end()), (1, 1)),
298 2 => assert_eq!((mat.start(), mat.end()), (2, 3)),
299 i => panic!("Expected 3 captures, got {}", i + 1),
300 }
301 }
302 }
303
304 #[test]
305 fn find_iter_zero_length_longer_codepoint() {
306 let text = "é1é";
307
308 for (i, mat) in common::regex(r"\d*(?=é)").find_iter(text).enumerate() {
309 let mat = mat.unwrap();
310
311 match i {
312 0 => assert_eq!((mat.start(), mat.end()), (0, 0)),
313 1 => assert_eq!((mat.start(), mat.end()), (2, 3)),
314 i => panic!("Expected 2 captures, got {}", i + 1),
315 }
316 }
317 }
318
319 #[test]
320 fn find_iter_continue_from_previous_match_end() {
321 let text = "1122 33";
322
323 for (i, mat) in common::regex(r"\G(\d)\d").find_iter(text).enumerate() {
324 let mat = mat.unwrap();
325
326 match i {
327 0 => assert_eq!((mat.start(), mat.end()), (0, 2)),
328 1 => assert_eq!((mat.start(), mat.end()), (2, 4)),
329 i => panic!("Expected 2 results, got {}", i + 1),
330 }
331 }
332 }
333
334 #[test]
335 fn find_iter_continue_from_previous_match_end_with_zero_width_match() {
336 let text = "1122 33";
337
338 for (i, mat) in common::regex(r"\G\d*").find_iter(text).enumerate() {
339 let mat = mat.unwrap();
340
341 match i {
342 0 => assert_eq!((mat.start(), mat.end()), (0, 4)),
343 i => panic!("Expected 1 result, got {}", i + 1),
344 }
345 }
346 }
347
348 #[test]
349 fn find_iter_continue_from_previous_match_end_inside_alternation_continue_last() {
350 // Test that \G in alternation doesn't cause overzealous early bailout
351 // Pattern: abc|\G1
352 // The alternation allows matching "abc" at any position,
353 // while \G1 only matches "1" at the continuation position
354 let text = "1hello1 abc1";
355
356 for (i, mat) in common::regex(r"abc|\G1").find_iter(text).enumerate() {
357 let mat = mat.unwrap();
358
359 // Expected matches:
360 // 1. "1" at position 0 (via \G1 branch at start)
361 // 2. "abc" at position 8 (via abc branch)
362 // 3. "1" at position 11 (via \G1 branch continuing from previous match end)
363 match i {
364 0 => assert_eq!((mat.start(), mat.end()), (0, 1)),
365 1 => assert_eq!((mat.start(), mat.end()), (8, 11)),
366 2 => assert_eq!((mat.start(), mat.end()), (11, 12)),
367 i => panic!("Expected 3 results, got {}", i + 1),
368 }
369 }
370 }
371
372 #[test]
373 fn find_iter_continue_from_previous_match_end_inside_alternation_continue_first() {
374 // Test with \G branch first in alternation: \G\d+|abc
375 // This ensures the optimization doesn't incorrectly bail out
376 let text = "123abc456";
377
378 for (i, mat) in common::regex(r"\G\d+|abc").find_iter(text).enumerate() {
379 let mat = mat.unwrap();
380
381 // Expected matches:
382 // 1. "123" at position 0 (via \G\d+ branch at start)
383 // 2. "abc" at position 3 (via abc branch continuing from previous match end)
384 // 3. "456" at position 6 (via \G\d+ branch continuing from previous match end)
385 match i {
386 0 => assert_eq!((mat.start(), mat.end()), (0, 3)),
387 1 => assert_eq!((mat.start(), mat.end()), (3, 6)),
388 2 => assert_eq!((mat.start(), mat.end()), (6, 9)),
389 i => panic!("Expected 3 results, got {}", i + 1),
390 }
391 }
392 }
393
394 #[test]
395 fn find_iter_continue_from_previous_match_end_inside_conditional_lookahead() {
396 let text = "1a23ba456a";
397
398 for (i, mat) in common::regex(r"(?((?=\G))a|b)").find_iter(text).enumerate() {
399 let mat = mat.unwrap();
400
401 // Expected matches:
402 // 1. "b" at position 4 (because \G didn't match)
403 // 2. "a" at position 5 (because \G matches)
404 match i {
405 0 => assert_eq!((mat.start(), mat.end()), (4, 5)),
406 1 => assert_eq!((mat.start(), mat.end()), (5, 6)),
407 i => panic!("Expected 2 results, got {}", i + 1),
408 }
409 }
410 }
411
412 #[test]
413 fn find_iter_continue_from_previous_match_end_inside_conditional_lookbehind() {
414 let text = "1a23bab456a";
415
416 for (i, mat) in common::regex(r"(?((?!\G))a|b)").find_iter(text).enumerate() {
417 let mat = mat.unwrap();
418
419 // Expected matches:
420 // 1. "a" at position 1 (because \G didn't match)
421 // 2. "a" at position 5 (because \G didn't match)
422 // 3. "b" at position 6 (because \G did match)
423 // 4. "a" at position 10 (because \G didn't match)
424 match i {
425 0 => assert_eq!((mat.start(), mat.end()), (1, 2)),
426 1 => assert_eq!((mat.start(), mat.end()), (5, 6)),
427 2 => assert_eq!((mat.start(), mat.end()), (6, 7)),
428 3 => assert_eq!((mat.start(), mat.end()), (10, 11)),
429 i => panic!("Expected 4 results, got {}", i + 1),
430 }
431 }
432 }
433
434 #[test]
435 fn find_iter_continue_from_previous_match_end_single_match() {
436 // Test basic \G behavior with find_iter - should only match at start
437 let text = "123 456 789";
438
439 // Should only match at position 0
440 for (i, mat) in common::regex(r"\G\d+").find_iter(text).enumerate() {
441 let mat = mat.unwrap();
442
443 match i {
444 0 => assert_eq!((mat.start(), mat.end()), (0, 3)),
445 i => panic!("Expected 1 result, got {}", i + 1),
446 }
447 }
448 }
449
450 #[test]
451 fn find_iter_attributes() {
452 let text = "ab1c2";
453 let regex = common::regex(r"\d*(?=[a-z])");
454
455 let matches = regex.find_iter(text);
456
457 assert_eq!(matches.text(), text);
458 assert_eq!(regex.as_str(), matches.regex().as_str());
459 }
460
461 #[test]
462 fn find_iter_empty_repeat_issue70() {
463 fn assert_expected_matches(pattern: &str) {
464 let text = "a\naaa\n";
465 let regex = common::regex(pattern);
466
467 let matches: Vec<_> = regex.find_iter(text).collect();
468 assert_eq!(matches.len(), 4);
469
470 for i in 0..matches.len() {
471 let mat = &matches[i].as_ref().unwrap();
472 match i {
473 0 => assert_eq!((mat.start(), mat.end()), (0, 0)),
474 1 => assert_eq!((mat.start(), mat.end()), (2, 2)),
475 2 => assert_eq!((mat.start(), mat.end()), (3, 5)),
476 3 => assert_eq!((mat.start(), mat.end()), (6, 6)),
477 i => panic!("Expected 4 results, got {}", i + 1),
478 }
479 }
480 }
481
482 assert_expected_matches(r"(?m)(?:^|a)+");
483 assert_expected_matches(r"(?m)(?:^|a)(?:^|a)*");
484 assert_expected_matches(r"(?m)(?>)(?:^|a)+");
485 assert_expected_matches(r"(?m)(?>)(?:^|a)(?:^|a)*");
486 }
487
488 #[test]
489 fn find_iter_empty_repeat_non_greedy_issue70() {
490 fn assert_expected_matches(pattern: &str) {
491 let text = "a\naaa\n";
492 let regex = common::regex(pattern);
493
494 let matches: Vec<_> = regex.find_iter(text).collect();
495 assert_eq!(matches.len(), 5);
496
497 for i in 0..matches.len() {
498 let mat = &matches[i].as_ref().unwrap();
499 match i {
500 0 => assert_eq!((mat.start(), mat.end()), (0, 0)),
501 1 => assert_eq!((mat.start(), mat.end()), (2, 2)),
502 2 => assert_eq!((mat.start(), mat.end()), (3, 4)),
503 3 => assert_eq!((mat.start(), mat.end()), (4, 5)),
504 4 => assert_eq!((mat.start(), mat.end()), (6, 6)),
505 i => panic!("Expected 4 results, got {}", i + 1),
506 }
507 }
508 }
509
510 assert_expected_matches(r"(?m)(?:^|a)+?");
511 assert_expected_matches(r"(?m)(?:^|a)(?:^|a)*?");
512 assert_expected_matches(r"(?m)(?>)(?:^|a)+?");
513 assert_expected_matches(r"(?m)(?>)(?:^|a)(?:^|a)*?");
514 }
515
516 #[test]
517 fn find_iter_empty_repeat_anchored_non_greedy_issue70() {
518 fn assert_expected_matches(pattern: &str) {
519 let text = "a\naaa\n";
520 let regex = common::regex(pattern);
521
522 let matches: Vec<_> = regex.find_iter(text).collect();
523 assert_eq!(matches.len(), 3);
524
525 for i in 0..matches.len() {
526 let mat = &matches[i].as_ref().unwrap();
527 match i {
528 0 => assert_eq!((mat.start(), mat.end()), (0, 1)),
529 1 => assert_eq!((mat.start(), mat.end()), (2, 5)),
530 2 => assert_eq!((mat.start(), mat.end()), (6, 6)),
531 i => panic!("Expected 3 results, got {}", i + 1),
532 }
533 }
534 }
535
536 assert_expected_matches(r"(?m)(?:^|a)+?$");
537 assert_expected_matches(r"(?m)(?:^|a)(?:^|a)*?$");
538 assert_expected_matches(r"(?m)(?>)(?:^|a)+?$");
539 assert_expected_matches(r"(?m)(?>)(?:^|a)(?:^|a)*?$");
540 }
541
542 #[test]
543 fn find_iter_collect_when_backtrack_limit_hit() {
544 use fancy_regex::Error;
545 use fancy_regex::RuntimeError;
546
547 let r = RegexBuilder::new("(x+x+)+(?>y)")
548 .backtrack_limit(1)
549 .build()
550 .unwrap();
551 let result: Vec<_> = r.find_iter("xxxxxxxxxxy").collect();
552 assert_eq!(result.len(), 1);
553 assert!(result[0].is_err());
554 match &result[0].as_ref().err() {
555 Some(Error::RuntimeError(RuntimeError::BacktrackLimitExceeded)) => {}
556 _ => panic!("Expected RuntimeError::BacktrackLimitExceeded"),
557 }
558 }
559
560 #[test]
561 fn find_conditional() {
562 assert_eq!(find(r"(?(ab)c|d)", "acd"), Some((2, 3)));
563 assert_eq!(find(r"(a)?b(?(1)c|d)", "abc"), Some((0, 3)));
564 assert_eq!(find(r"(a)?b(?(1)c|d)", "abd"), Some((1, 3)));
565 }
566
567 #[test]
568 fn find_endtext_before_newlines() {
569 assert_eq!(find(r"\Z", "hello\nworld\n\n\n"), Some((11, 11)));
570 }
571
572 #[test]
573 fn find_endtext_ignore_trailing_newlines_non_crlf() {
574 // \Z without CRLF mode: only bare \n chars are skipped at the end.
575 // "abc\n\n" — \Z matches at position 3 (before the trailing newlines)
576 assert_eq!(find(r"\Z", "abc\n\n"), Some((3, 3)));
577 // No trailing newlines: \Z matches at the very end
578 assert_eq!(find(r"\Z", "abc"), Some((3, 3)));
579 // \r\n at the end: in non-CRLF mode the \r is NOT treated as a newline for \Z,
580 // so \Z matches just before the trailing \n, not before the \r\n pair.
581 assert_eq!(find(r"\Z", "abc\r\n"), Some((4, 4)));
582 }
583
584 #[test]
585 fn find_endtext_ignore_trailing_newlines_crlf() {
586 // (?R) enables CRLF mode; \Z should then treat \r as part of trailing newlines too.
587 assert_eq!(
588 RegexBuilder::new(r"\Z")
589 .crlf(true)
590 .build()
591 .unwrap()
592 .find("abc\r\n")
593 .unwrap()
594 .map(|m| (m.start(), m.end())),
595 Some((3, 3))
596 );
597 assert_eq!(
598 RegexBuilder::new(r"\Z")
599 .crlf(true)
600 .build()
601 .unwrap()
602 .find("abc\r\r")
603 .unwrap()
604 .map(|m| (m.start(), m.end())),
605 Some((3, 3))
606 );
607 // bare \n still works in CRLF mode
608 assert_eq!(
609 RegexBuilder::new(r"\Z")
610 .crlf(true)
611 .build()
612 .unwrap()
613 .find("abc\n")
614 .unwrap()
615 .map(|m| (m.start(), m.end())),
616 Some((3, 3))
617 );
618 }
619
620 #[test]
621 fn find_endtext_ignore_trailing_newlines_crlf_seek() {
622 // (?R) enables CRLF mode; \Z should then treat \r as part of trailing newlines too.
623 assert_eq!(
624 RegexBuilder::new(r"\Z")
625 .crlf(true)
626 .seek(true) // TODO: ideally we would test every pattern with seek on and off automatically to compare them. Otherwise if we change the default, we might miss test case combinations in our tests.
627 .build()
628 .unwrap()
629 .find("abc\r\n")
630 .unwrap()
631 .map(|m| (m.start(), m.end())),
632 Some((3, 3))
633 );
634 assert_eq!(
635 RegexBuilder::new(r"\Z")
636 .crlf(true)
637 .seek(true)
638 .build()
639 .unwrap()
640 .find("abc\r\r")
641 .unwrap()
642 .map(|m| (m.start(), m.end())),
643 Some((3, 3))
644 );
645 // bare \n still works in CRLF mode
646 assert_eq!(
647 RegexBuilder::new(r"\Z")
648 .crlf(true)
649 .seek(true)
650 .build()
651 .unwrap()
652 .find("abc\n")
653 .unwrap()
654 .map(|m| (m.start(), m.end())),
655 Some((3, 3))
656 );
657 }
658
659 #[test]
660 fn continue_from_previous_match_with_lookahead_before() {
661 let text = "123abc";
662
663 // Lookahead doesn't consume, so \G should still be at position 0
664 assert_eq!(find(r"(?=\d)\G\d+", text), Some((0, 3)));
665
666 // Lookahead fails, so whole match fails
667 assert_eq!(find(r"(?=[a-z])\G\d+", text), None);
668
669 // Negative lookahead passes (not a letter), \G continues
670 assert_eq!(find(r"(?![a-z])\G\d+", text), Some((0, 3)));
671
672 // Negative lookahead fails (is a digit), match fails
673 assert_eq!(find(r"(?!\d)\G\d+", text), None);
674 }
675
676 #[test]
677 fn continue_from_previous_match_in_alternation() {
678 // Pattern: \G in alternation - tests whether \G behaves correctly in branches
679 let text = "123abc";
680
681 // First branch with \G should match
682 assert_eq!(find(r"\G\d+|xyz", text), Some((0, 3)));
683
684 // Second branch should also work when first fails
685 assert_eq!(find(r"\Gxyz|\d+", text), Some((0, 3)));
686 assert_eq!(find(r"\D+|\G123", text), Some((0, 3)));
687 }
688
689 #[test]
690 fn continue_from_previous_match_fails_when_not_at_continue_position() {
691 // \G should fail when we're not at the position where the last match ended
692 let text = " 123";
693
694 // Starting match at position 0, but there's a space, so \G at position 0 followed by \d
695 // should not match because we'd need to skip the space
696 assert_eq!(find(r"\G\d+", text), None);
697 }
698
699 #[test]
700 fn continue_from_previous_match_at_min_position_zero() {
701 let text = "123abc";
702
703 assert_eq!(find(r"^x?\b(\G\d+)", text), Some((0, 3)));
704 assert_eq!(find(r"(?:^|\b)x?(\G\d+)", text), Some((0, 3)));
705 assert_eq!(find(r"(?:\G\d+|xyz)|abc", text), Some((0, 3)));
706 assert_eq!(find(r"(?=\d)(?=1)\G\d+", text), Some((0, 3)));
707 // Atomic group doesn't affect \G position checking
708 assert_eq!(find(r"(?>\G)\d+", "123abc"), Some((0, 3)));
709 }
710
711 #[test]
712 fn find_iter_continue_from_previous_match_end_with_keepout() {
713 // \G..\K produces zero-length matches because \K resets the reported start to
714 // after the two consumed characters. Iteration should continue matching across
715 // the whole string, advancing two bytes at a time, not stop after the first match.
716 let text = "aabbcc";
717
718 for (i, mat) in common::regex(r"\G..\K").find_iter(text).enumerate() {
719 let mat = mat.unwrap();
720
721 match i {
722 0 => assert_eq!((mat.start(), mat.end()), (2, 2)),
723 1 => assert_eq!((mat.start(), mat.end()), (5, 5)),
724 i => panic!("Expected 2 results, got {}", i + 1),
725 }
726 }
727 }
728
729 #[test]
730 fn find_not_empty_skips_zero_length_match() {
731 // \d* on text that doesn't start with a digit: normal mode matches empty at position 0,
732 // find_not_empty mode rejects the zero-length match.
733 let pattern = r"\d*";
734 let text = "hello";
735
736 let normal = common::regex(pattern);
737 assert_eq!(
738 normal.find(text).unwrap().map(|m| (m.start(), m.end())),
739 Some((0, 0)),
740 );
741
742 let not_empty = RegexBuilder::new(pattern)
743 .find_not_empty(true)
744 .build()
745 .unwrap();
746 assert_eq!(
747 not_empty.find(text).unwrap().map(|m| (m.start(), m.end())),
748 None,
749 );
750 }
751
752 #[test]
753 fn find_not_empty_find_iter() {
754 // With find_iter, find_not_empty should keep non-empty matches but stop
755 // when a zero-length match is encountered (returning None stops the iterator).
756 let pattern = r"\d*";
757 let text = "1a2";
758
759 // Normal mode: "1" at 0-1, empty at 1-1 skipped (adjacent to last match end),
760 // "2" at 2-3, empty at 3-3 skipped (adjacent to last match end), done.
761 let normal: Vec<(usize, usize)> = common::regex(pattern)
762 .find_iter(text)
763 .map(|m| {
764 let m = m.unwrap();
765 (m.start(), m.end())
766 })
767 .collect();
768 assert_eq!(normal, vec![(0, 1), (2, 3)]);
769
770 // find_not_empty: "1" at (0,1) is non-empty → kept. Next search at pos 1: \d* matches ""
771 // at (1,1), find_not_empty rejects and advances past the empty match. At pos 2: \d*
772 // matches "2" at (2,3), which is non-empty → kept. Both non-empty matches are yielded.
773 let not_empty = RegexBuilder::new(pattern)
774 .find_not_empty(true)
775 .build()
776 .unwrap();
777 let filtered: Vec<(usize, usize)> = not_empty
778 .find_iter(text)
779 .map(|m| {
780 let m = m.unwrap();
781 (m.start(), m.end())
782 })
783 .collect();
784 assert_eq!(filtered, vec![(0, 1), (2, 3)]);
785 }
786
787 #[test]
788 fn find_not_empty_captures_iter() {
789 // Same as find_not_empty_find_iter but using captures_iter to verify
790 // the captures path also advances past empty matches.
791 let pattern = r"(\d*)";
792 let text = "1a2";
793
794 let not_empty = RegexBuilder::new(pattern)
795 .find_not_empty(true)
796 .build()
797 .unwrap();
798 let filtered: Vec<(usize, usize)> = not_empty
799 .captures_iter(text)
800 .map(|c| {
801 let c = c.unwrap();
802 let m = c.get(0).unwrap();
803 (m.start(), m.end())
804 })
805 .collect();
806 assert_eq!(filtered, vec![(0, 1), (2, 3)]);
807 }
808
809 #[test]
810 fn find_not_empty_fancy_path() {
811 // Use a lookbehind to force the fancy/VM path, then verify find_not_empty works there too.
812 // (?<=^)\d* matches an empty string of digits at the start of text.
813 let pattern = r"(?<=^)\d*";
814 let text = "hello";
815
816 let normal = common::regex(pattern);
817 assert_eq!(
818 normal.find(text).unwrap().map(|m| (m.start(), m.end())),
819 Some((0, 0)),
820 );
821
822 let not_empty = RegexBuilder::new(pattern)
823 .find_not_empty(true)
824 .build()
825 .unwrap();
826 assert_eq!(
827 not_empty.find(text).unwrap().map(|m| (m.start(), m.end())),
828 None,
829 );
830 }
831
832 #[test]
833 fn find_not_empty_fancy_find_iter() {
834 // Atomic group forces the fancy/VM path.
835 // (?>\d*) behaves like \d* but via the backtracking VM.
836 let pattern = r"(?>\d*)";
837 let text = "1a2";
838
839 // Normal mode: same as \d* — "1" at 0-1, "2" at 2-3
840 // (empty matches adjacent to the previous match end are skipped by find_iter)
841 let normal: Vec<(usize, usize)> = common::regex(pattern)
842 .find_iter(text)
843 .map(|m| {
844 let m = m.unwrap();
845 (m.start(), m.end())
846 })
847 .collect();
848 assert_eq!(normal, vec![(0, 1), (2, 3)]);
849
850 // find_not_empty with the fancy/VM path: the VM's unanchored search loop
851 // (Split/Any/Jmp preamble) allows it to advance past positions where the
852 // pattern would produce an empty match. So unlike the Wrap path, the VM
853 // at pos 1 rejects the empty match via OPTION_FIND_NOT_EMPTY but then
854 // advances and finds "2" at (2,3). Both non-empty matches are yielded.
855 let not_empty = RegexBuilder::new(pattern)
856 .find_not_empty(true)
857 .build()
858 .unwrap();
859 let filtered: Vec<(usize, usize)> = not_empty
860 .find_iter(text)
861 .map(|m| {
862 let m = m.unwrap();
863 (m.start(), m.end())
864 })
865 .collect();
866 assert_eq!(filtered, vec![(0, 1), (2, 3)]);
867 }
868
869 #[test]
870 fn find_not_empty_trailing_lookahead_with_variable_group0() {
871 // \d*(?=x) optimizes to (\d*)x with explicit_capture_group_0.
872 // The user-visible match is explicit group 0 (\d*). When \d* matches empty,
873 // find_not_empty should reject the match even though the physical match
874 // (including the "x") is non-empty.
875 let pattern = r"\d*(?=x)";
876 let text = "xhello";
877
878 // Normal mode: matches empty \d* followed by lookahead for x → match at (0, 0)
879 let normal = common::regex(pattern);
880 assert_eq!(
881 normal.find(text).unwrap().map(|m| (m.start(), m.end())),
882 Some((0, 0)),
883 );
884
885 // find_not_empty: the user-visible match (group 0) is empty → rejected
886 let not_empty = RegexBuilder::new(pattern)
887 .find_not_empty(true)
888 .build()
889 .unwrap();
890 assert_eq!(
891 not_empty.find(text).unwrap().map(|m| (m.start(), m.end())),
892 None,
893 );
894
895 // But with digits before the x, the match is non-empty → accepted
896 let text_with_digits = "12xhello";
897 assert_eq!(
898 not_empty
899 .find(text_with_digits)
900 .unwrap()
901 .map(|m| (m.start(), m.end())),
902 Some((0, 2)),
903 );
904 }
905
906 #[test]
907 fn find_not_empty_alternation_with_empty_branch() {
908 // (?:|a|b) can match empty, "a", or "b". Without find_not_empty, the empty branch wins
909 // at position 0 (leftmost, first alternative). With find_not_empty, the empty match at
910 // position 0 must be skipped, and the pattern should then find "a" or "b".
911 let pattern = r"(?:|a|b)";
912
913 // Normal mode: empty match at position 0
914 let normal = common::regex(pattern);
915 assert_eq!(
916 normal.find("a").unwrap().map(|m| (m.start(), m.end())),
917 Some((0, 0)),
918 );
919
920 // find_not_empty mode: empty match rejected; "a" found instead
921 let not_empty = RegexBuilder::new(pattern)
922 .find_not_empty(true)
923 .build()
924 .unwrap();
925 assert_eq!(
926 not_empty.find("a").unwrap().map(|m| (m.start(), m.end())),
927 Some((0, 1)),
928 );
929 assert_eq!(
930 not_empty.find("b").unwrap().map(|m| (m.start(), m.end())),
931 Some((0, 1)),
932 );
933 assert_eq!(
934 not_empty.find("c").unwrap().map(|m| (m.start(), m.end())),
935 None,
936 );
937 }
938
939 #[test]
940 fn find_not_empty_with_keep_out() {
941 // The find_not_empty check compares what the engine consumed, regardless of the match reported,
942 // which could be affected by \K.
943 let not_empty = RegexBuilder::new(r"a\Kb")
944 .find_not_empty(true)
945 .build()
946 .unwrap();
947 assert_eq!(
948 not_empty.find("ab").unwrap().map(|m| (m.start(), m.end())),
949 Some((1, 2)),
950 );
951
952 // `ab\K` physically consumes "ab" (ix advances to 2), so it is accepted as non-empty.
953 // `\K` resets saves[0] to 2, giving the reported span (2, 2).
954 let not_empty_abk = RegexBuilder::new(r"ab\K")
955 .find_not_empty(true)
956 .build()
957 .unwrap();
958 assert_eq!(
959 not_empty_abk
960 .find("ab")
961 .unwrap()
962 .map(|m| (m.start(), m.end())),
963 Some((2, 2)),
964 );
965 }
966
967 #[test]
968 fn find_not_empty_with_continue_from_previous_match_end() {
969 // \G\d+ with find_not_empty: only matches where the previous match ended and
970 // the match is non-empty. On "1122 33", \G matches at position 0; "1122" is
971 // consumed (non-empty → accepted). The next call starts at pos=4 (space),
972 // \G succeeds but \d+ fails → no further matches.
973 let not_empty = RegexBuilder::new(r"\G\d+")
974 .find_not_empty(true)
975 .build()
976 .unwrap();
977 let matches: Vec<_> = not_empty
978 .find_iter("1122 33")
979 .map(|m| {
980 let m = m.unwrap();
981 (m.start(), m.end())
982 })
983 .collect();
984 assert_eq!(matches, vec![(0, 4)]);
985
986 // \G\d* can produce an empty match after the digits run out. find_not_empty
987 // must reject that empty match. On "1122 33", after the non-empty "1122"
988 // match the next attempt is at position 4 (space); \G\d* would match empty
989 // there, but find_not_empty rejects it, so no further matches are produced.
990 let not_empty_star = RegexBuilder::new(r"\G\d*")
991 .find_not_empty(true)
992 .build()
993 .unwrap();
994 let matches_star: Vec<_> = not_empty_star
995 .find_iter("1122 33")
996 .map(|m| {
997 let m = m.unwrap();
998 (m.start(), m.end())
999 })
1000 .collect();
1001 assert_eq!(matches_star, vec![(0, 4)]);
1002 }
1003
1004 #[test]
1005 fn find_not_empty_with_continue_from_previous_match_end_and_keep_out() {
1006 // \G..\K produces a zero-length reported span (saves[0] reset to after the
1007 // two consumed bytes), but physically consumes two characters. With
1008 // find_not_empty the check is `ix == match_attempt_start`: since two bytes
1009 // were consumed, ix > match_attempt_start and the match is accepted despite
1010 // the reported span being zero-length.
1011 let not_empty = RegexBuilder::new(r"\G..\K")
1012 .find_not_empty(true)
1013 .build()
1014 .unwrap();
1015 let matches: Vec<_> = not_empty
1016 .find_iter("aabbcc")
1017 .map(|m| {
1018 let m = m.unwrap();
1019 (m.start(), m.end())
1020 })
1021 .collect();
1022 // Each match physically consumes 2 bytes; \K resets the reported start to
1023 // the physical end, yielding zero-length spans. The iterator advances by 1
1024 // after each zero-length match (OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH), so the pattern
1025 // matches at positions (2,2) and (5,5), mirroring the behavior without find_not_empty.
1026 assert_eq!(matches, vec![(2, 2), (5, 5)]);
1027 }
1028
1029 #[test]
1030 fn find_not_empty_with_anchored_pattern() {
1031 // ^-anchored patterns with find_not_empty go through the VM path (because
1032 // find_not_empty forces the VM) but do NOT emit a SplitUnanchored preamble
1033 // (the pattern is compiled as anchored). match_attempt_start stays at pos,
1034 // so ix == match_attempt_start still correctly detects the empty match.
1035 let not_empty = RegexBuilder::new(r"^\d*")
1036 .find_not_empty(true)
1037 .build()
1038 .unwrap();
1039
1040 // No leading digits → empty match at position 0 → rejected
1041 assert_eq!(
1042 not_empty
1043 .find("hello")
1044 .unwrap()
1045 .map(|m| (m.start(), m.end())),
1046 None,
1047 );
1048
1049 // Leading digits → non-empty match at position 0 → accepted
1050 assert_eq!(
1051 not_empty
1052 .find("123hello")
1053 .unwrap()
1054 .map(|m| (m.start(), m.end())),
1055 Some((0, 3)),
1056 );
1057 }
1058
1059 #[test]
1060 fn find_from_pos_past_end_wrap() {
1061 let re = RegexBuilder::new(r"^(<{7})(?:\s+(\S.*?))?$\n?")
1062 .oniguruma_mode(true)
1063 .build()
1064 .unwrap();
1065 let result = re.find_from_pos("ab", 12);
1066 assert_matches!(result, Ok(None));
1067 }
1068
1069 #[test]
1070 fn find_from_pos_past_end_fancy() {
1071 let re = RegexBuilder::new(r"(?<=a)b")
1072 .oniguruma_mode(true)
1073 .build()
1074 .unwrap();
1075 let result = re.find_from_pos("ab", 12);
1076 assert_matches!(result, Ok(None));
1077 }
1078
1079 #[test]
1080 fn find_from_pos_at_end_still_runs() {
1081 let re = RegexBuilder::new("$").oniguruma_mode(true).build().unwrap();
1082 let result = re.find_from_pos("ab", 2).unwrap();
1083 assert!(result.is_some(), "pattern `$` must match at end-of-text");
1084 }
1085
1086 #[test]
1087 fn oniguruma_swapped_quantifier_order_is_possessive() {
1088 let re = RegexBuilder::new("x{3,0}x")
1089 .oniguruma_mode(true)
1090 .build()
1091 .unwrap();
1092 let result = re.find_from_pos("xx", 0).unwrap();
1093 assert!(
1094 result.is_none(),
1095 "swapped quantifier order in Oniguruma mode should make it possessive"
1096 );
1097 }
1098
1099 #[test]
1100 fn oniguruma_plus_after_quantifier() {
1101 let re = RegexBuilder::new("^x{2}+$")
1102 .oniguruma_mode(true)
1103 .build()
1104 .unwrap();
1105 let result = re.find_from_pos("xxxx", 0).unwrap();
1106 assert!(result.is_some(), "quantifier should be repeated");
1107
1108 let re = RegexBuilder::new("^x{0,3}+$")
1109 .oniguruma_mode(true)
1110 .build()
1111 .unwrap();
1112 let result = re.find_from_pos("xx", 0).unwrap();
1113 assert!(result.is_some(), "quantifier should be repeated");
1114 }
1115
1116 #[test]
1117 fn find_from_pos_startline_rejected_after_trailing_newline_at_eof() {
1118 let re = RegexBuilder::new("^")
1119 .oniguruma_mode(true)
1120 .multi_line(true)
1121 .build()
1122 .unwrap();
1123 let result = re.find_from_pos("ab\n", 3).unwrap();
1124 assert!(
1125 result.is_none(),
1126 "pattern `^` must not match at end-of-text after a trailing newline"
1127 );
1128 }
1129
1130 #[test]
1131 fn find_input_wrap_range_keeps_word_boundary_context() {
1132 assert_eq!(
1133 common::assert_find_input(r"\bat\b", "batter", 0, 1..3),
1134 None
1135 );
1136 assert_eq!(
1137 common::assert_find_input(r"\bat\b", "batter at", 0, 7..9),
1138 Some((7, 9))
1139 );
1140 }
1141
1142 #[test]
1143 fn find_input_wrap_range_handles_multiline_anchor_and_end_anchor() {
1144 assert_eq!(
1145 common::assert_find_input(r"(?m)^foo$", "xx\nfoo\nzz", 0, 3..6),
1146 Some((3, 6))
1147 );
1148 assert_eq!(common::assert_find_input(r"$", "ab", 0, 2..2), Some((2, 2)));
1149 assert_eq!(
1150 common::assert_find_input(r"\z", "ab", 0, 2..2),
1151 Some((2, 2))
1152 );
1153 }
1154
1155 #[test]
1156 fn find_input_fancy_range_allows_lookaround_outside_range() {
1157 assert_eq!(
1158 common::assert_find_input(r"(?=(foo))\1(?=bar)", "foobar", 0, 0..3),
1159 Some((0, 3))
1160 );
1161 assert_eq!(
1162 common::assert_find_input(r"(?<=foo)bar", "foobar", 3, 3..6),
1163 Some((3, 6))
1164 );
1165 }
1166
1167 #[test]
1168 fn find_iter_input_respects_range_for_empty_matches() {
1169 let re = common::regex(r"(?m)^");
1170 let text = "a\nb\n";
1171 let spans: Vec<_> = re
1172 .find_iter_input(RegexInput::new(text).range(2..4))
1173 .map(|m| {
1174 let m = m.unwrap();
1175 (m.start(), m.end())
1176 })
1177 .collect();
1178 assert_eq!(spans, vec![(2, 2), (4, 4)]);
1179 }
1180
1181 #[test]
1182 fn find_input_text_boundary_overrides() {
1183 let re = RegexBuilder::new(r"\Afoo\z")
1184 .allow_input_assertion_overrides(true)
1185 .build()
1186 .unwrap();
1187 let re_bytes = RegexBuilder::new(r"\Afoo\z")
1188 .bytes_mode(BytesMode::Ascii)
1189 .allow_input_assertion_overrides(true)
1190 .build()
1191 .unwrap();
1192 assert_eq!(
1193 re.find_input(RegexInput::new("foo").start_text(false).end_text(false))
1194 .unwrap()
1195 .map(|m| (m.start(), m.end())),
1196 None
1197 );
1198 assert_eq!(
1199 re_bytes
1200 .find_input(
1201 RegexInput::new("foo".as_bytes())
1202 .start_text(false)
1203 .end_text(false)
1204 )
1205 .unwrap()
1206 .map(|m| (m.start(), m.end())),
1207 None
1208 );
1209 assert_eq!(
1210 re.find_input(RegexInput::new("foo").start_text(true).end_text(true))
1211 .unwrap()
1212 .map(|m| (m.start(), m.end())),
1213 Some((0, 3))
1214 );
1215 assert_eq!(
1216 re_bytes
1217 .find_input(
1218 RegexInput::new("foo".as_bytes())
1219 .start_text(true)
1220 .end_text(true)
1221 )
1222 .unwrap()
1223 .map(|m| (m.start(), m.end())),
1224 Some((0, 3))
1225 );
1226 }
1227
1228 #[test]
1229 fn find_iter_input_continue_from_previous_match_end_override() {
1230 let re = RegexBuilder::new(r"\G")
1231 .allow_input_assertion_overrides(true)
1232 .build()
1233 .unwrap();
1234 let re_bytes = RegexBuilder::new(r"\G")
1235 .bytes_mode(BytesMode::Ascii)
1236 .allow_input_assertion_overrides(true)
1237 .build()
1238 .unwrap();
1239 let text = "ab";
1240 let default_spans: Vec<_> = re
1241 .find_iter_input(RegexInput::new(text))
1242 .map(|m| {
1243 let m = m.unwrap();
1244 (m.start(), m.end())
1245 })
1246 .collect();
1247 assert_eq!(default_spans, vec![(0, 0)]);
1248 let default_spans_bytes: Vec<_> = re_bytes
1249 .find_iter_input(RegexInput::new(text.as_bytes()))
1250 .map(|m| {
1251 let m = m.unwrap();
1252 (m.start(), m.end())
1253 })
1254 .collect();
1255 assert_eq!(default_spans_bytes, default_spans);
1256
1257 let forced_false_spans: Vec<_> = re
1258 .find_iter_input(RegexInput::new(text).continue_from_previous_match_end(false))
1259 .map(|m| {
1260 let m = m.unwrap();
1261 (m.start(), m.end())
1262 })
1263 .collect();
1264 assert_eq!(forced_false_spans, vec![]);
1265 let forced_false_spans_bytes: Vec<_> = re_bytes
1266 .find_iter_input(RegexInput::new(text.as_bytes()).continue_from_previous_match_end(false))
1267 .map(|m| {
1268 let m = m.unwrap();
1269 (m.start(), m.end())
1270 })
1271 .collect();
1272 assert_eq!(forced_false_spans_bytes, forced_false_spans);
1273
1274 let forced_true_spans: Vec<_> = re
1275 .find_iter_input(RegexInput::new(text).continue_from_previous_match_end(true))
1276 .map(|m| {
1277 let m = m.unwrap();
1278 (m.start(), m.end())
1279 })
1280 .collect();
1281 assert_eq!(forced_true_spans, default_spans);
1282 let forced_true_spans_bytes: Vec<_> = re_bytes
1283 .find_iter_input(RegexInput::new(text.as_bytes()).continue_from_previous_match_end(true))
1284 .map(|m| {
1285 let m = m.unwrap();
1286 (m.start(), m.end())
1287 })
1288 .collect();
1289 assert_eq!(forced_true_spans_bytes, forced_true_spans);
1290 }
1291
1292 fn find(re: &str, text: &str) -> Option<(usize, usize)> {
1293 common::assert_find(re, text)
1294 }
1295
1296 fn find_str_only(re: &str, text: &str) -> Option<(usize, usize)> {
1297 find_match(re, text).map(|m| (m.start(), m.end()))
1298 }
1299
1300 fn find_match<'t>(re: &str, text: &'t str) -> Option<Match<'t>> {
1301 let regex = common::regex(re);
1302 let result = regex.find(text);
1303 assert!(
1304 result.is_ok(),
1305 "Expected find to succeed, but was {:?}",
1306 result
1307 );
1308 result.unwrap()
1309 }
1310
1311 /// Build a regex with the seek pre-filter enabled.
1312 fn seek_regex(re: &str) -> fancy_regex::Regex {
1313 let result = RegexBuilder::new(re).seek(true).build();
1314 assert!(
1315 result.is_ok(),
1316 "Expected regex '{}' to compile successfully with seek enabled, got {:?}",
1317 re,
1318 result.err()
1319 );
1320 result.unwrap()
1321 }
1322
1323 #[test]
1324 fn seek_backref_finds_match() {
1325 // The seek pattern inlines the group body ("abc") and jumps past irrelevant text.
1326 common::assert_seek_same(r"(abc)\1", "xxxabcabcyyy");
1327 common::assert_seek_same(r"(abc)\1", "xabcabcx");
1328 }
1329
1330 #[test]
1331 fn seek_overlapping_alternatives_finds_leftmost_match() {
1332 // https://github.com/rust-lang/regex/issues/1354
1333 let result = common::assert_seek_same(r".abb|b", "zabb");
1334 assert_eq!(result, Some((0, 4)));
1335 }
1336
1337 #[test]
1338 fn seek_negated_char_class_optional_finds_leftmost_match() {
1339 // https://github.com/rust-lang/regex/issues/1345
1340 let result = common::assert_seek_same(r"[^()]*(?:\([^()]*\))?[^()]*:", "$(:):");
1341 assert_eq!(result, Some((0, 5)));
1342 }
1343
1344 #[test]
1345 fn seek_backref_no_match() {
1346 common::assert_seek_same(r"(abc)\1", "xxxyyy");
1347 common::assert_seek_same(r"(abc)\1", "abcxabc");
1348 }
1349
1350 #[test]
1351 fn seek_matches_identical_to_default() {
1352 let cases: &[(&str, &str)] = &[
1353 // backref patterns
1354 (r"(\w+) \1", "hello hello world"),
1355 (r"(\w+) \1", "no match here"),
1356 (r"(a|b)\1", "aabb"),
1357 // lookahead
1358 (r"foo(?=bar)", "foobar"),
1359 (r"foo(?=bar)", "foobaz"),
1360 // lookbehind
1361 (r"(?<=foo)bar", "foobar"),
1362 (r"(?<=foo)bar", "bazbar"),
1363 // long haystack with rare match
1364 (
1365 r"(xyz)\1",
1366 &format!("{}{}", "abcdefghij".repeat(1000), "xyzxyz"),
1367 ),
1368 // long haystack with no match
1369 (r"(xyz)\1", &"abcdefghij".repeat(1000)),
1370 // literals
1371 (r"(?<=)\nbaz", "foobar\nbaz\ntest"),
1372 (r"(?<=)\tbaz", "foobar\n\tbaz\n\ttest"),
1373 ];
1374 for (re, text) in cases {
1375 common::assert_seek_same(re, text);
1376 }
1377 }
1378
1379 #[test]
1380 fn seek_find_iter_matches_identical_to_default() {
1381 let re = r"(\w+) \1";
1382 let text = "the the cat sat on on the mat mat";
1383
1384 let default_matches: Vec<_> = common::regex(re)
1385 .find_iter(text)
1386 .map(|m| m.unwrap())
1387 .map(|m| (m.start(), m.end()))
1388 .collect();
1389 let seek_matches: Vec<_> = seek_regex(re)
1390 .find_iter(text)
1391 .map(|m| m.unwrap())
1392 .map(|m| (m.start(), m.end()))
1393 .collect();
1394 assert_eq!(default_matches, seek_matches);
1395 }