-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcapture.ts
50 lines (45 loc) · 1.26 KB
/
capture.ts
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
import { encode } from '../encoder';
import type { EncodedRegex, RegexSequence } from '../types';
export type CaptureOptions = {
/**
* Name to be given to the capturing group.
*/
name?: string;
};
export interface Reference extends EncodedRegex {
name: string;
}
/**
* Creates a capturing group which allows the matched pattern to be available:
* - in the match results (`String.match`, `String.matchAll`, or `RegExp.exec`)
* - in the regex itself, through {@link ref}
*/
export function capture(sequence: RegexSequence, options?: CaptureOptions): EncodedRegex {
const name = options?.name;
if (name) {
return {
precedence: 'atom',
pattern: `(?<${name}>${encode(sequence).pattern})`,
};
}
return {
precedence: 'atom',
pattern: `(${encode(sequence).pattern})`,
};
}
/**
* Creates a reference, also known as backreference, which allows matching
* again the exact text that a capturing group previously matched.
*
* In order to form a valid regex, the reference must use the same name as
* a capturing group earlier in the expression.
*
* @param name - Name of the capturing group to reference.
*/
export function ref(name: string): Reference {
return {
precedence: 'atom',
pattern: `\\k<${name}>`,
name,
};
}