| 1 |
# Subroutines: reusable patterns with stable meaning |
| 2 |
|
| 3 |
## What is a subroutine |
| 4 |
|
| 5 |
Subroutines in fancy-regex are *compiled pattern definitions* that can be invoked safely and predictably. |
| 6 |
Any capture group can become a subroutine - it just needs to be "called". |
| 7 |
|
| 8 |
```regexp |
| 9 |
(?<num>\d*\.\d+|\d+) x \g<num> |
| 10 |
``` |
| 11 |
|
| 12 |
In the above example, a capture group called `num` is defined, to match numbers with or without decimal places. `\g<num>` executes the capture group again, without the author having to re-type the pattern inside it. |
| 13 |
The above pattern would match text like `5.2 x 6` for instance. |
| 14 |
|
| 15 |
Think of a subroutine as: |
| 16 |
|
| 17 |
- defined by a capture group |
| 18 |
- executed exactly the way the capture group was originally defined |
| 19 |
- reusable from multiple places |
| 20 |
|
| 21 |
## Side effects |
| 22 |
|
| 23 |
A subroutine call has one side-effect - it updates the capture group position, which affects backref matching etc. |
| 24 |
|
| 25 |
## Example |
| 26 |
|
| 27 |
Let's imagine a pattern which will match a digit and capture it into group 1. Then it will call that capture group as a subroutine. Then it will do a backref to group 1. |
| 28 |
|
| 29 |
This will match three consecutive digits. The 2nd and 3rd digits must be identical. |
| 30 |
|
| 31 |
```rust |
| 32 |
use fancy_regex::{Error, Regex}; |
| 33 |
|
| 34 |
let re = Regex::new(r"(\d)\g<1>\1")?; |
| 35 |
let result = re.captures("foo 711")?; |
| 36 |
|
| 37 |
let captures = result.unwrap(); |
| 38 |
|
| 39 |
let m = captures.get(0).unwrap(); |
| 40 |
|
| 41 |
assert_eq!(m.start(), 4); |
| 42 |
assert_eq!(m.end(), 7); |
| 43 |
assert_eq!(m.as_str(), "711"); |
| 44 |
|
| 45 |
let group = captures.get(1).unwrap(); |
| 46 |
assert_eq!(group.as_str(), "1"); |
| 47 |
|
| 48 |
assert!(!re.is_match("foo 717")?); |
| 49 |
|
| 50 |
# Ok::<(), Error>(()) |
| 51 |
``` |
| 52 |
|
| 53 |
In the above example, 7 was stored in capture group 1. Then it was replaced with 1 by the subroutine call. Then the backreference to group 1 can only match the literal `1`. |
| 54 |
|
| 55 |
## Side effect edge cases |
| 56 |
|
| 57 |
Also, in a lookbehind, a subroutine call would not update the capture group position when the currently stored position for that capture group is further to the right in the haystack. i.e. right-most captures take precedence. |