1
1
import type { RegexElement } from './components/types' ;
2
2
import { encodeSequence } from './encoder/encoder' ;
3
+ import { isRegexElement } from './utils' ;
4
+
5
+ export interface RegexFlags {
6
+ /** Global search. */
7
+ global ?: boolean ;
8
+ /** Case-insensitive search. */
9
+ ignoreCase ?: boolean ;
10
+ /** Allows ^ and $ to match newline characters. */
11
+ multiline ?: boolean ;
12
+ /** Generate indices for substring matches. */
13
+ hasIndices ?: boolean ;
14
+ /** Perform a "sticky" search that matches starting at the current position in the target string. */
15
+ sticky ?: boolean ;
16
+ }
3
17
4
18
/**
5
19
* Generate RegExp object for elements.
6
20
*
7
21
* @param elements
8
22
* @returns
9
23
*/
10
- export function buildRegex ( ...elements : Array < RegexElement | string > ) : RegExp {
11
- const pattern = encodeSequence ( elements ) . pattern ;
12
- return new RegExp ( pattern ) ;
24
+ export function buildRegex ( ...elements : Array < RegexElement | string > ) : RegExp ;
25
+ export function buildRegex (
26
+ flags : RegexFlags ,
27
+ ...elements : Array < RegexElement | string >
28
+ ) : RegExp ;
29
+ export function buildRegex (
30
+ first : RegexFlags | RegexElement | string ,
31
+ ...rest : Array < RegexElement | string >
32
+ ) : RegExp {
33
+ if ( typeof first === 'string' || isRegexElement ( first ) ) {
34
+ return buildRegex ( { } , first , ...rest ) ;
35
+ }
36
+
37
+ const pattern = encodeSequence ( rest ) . pattern ;
38
+ const flags = encodeFlags ( first ) ;
39
+ return new RegExp ( pattern , flags ) ;
13
40
}
14
41
15
42
/**
@@ -22,3 +49,24 @@ export function buildPattern(
22
49
) : string {
23
50
return encodeSequence ( elements ) . pattern ;
24
51
}
52
+
53
+ function encodeFlags ( flags : RegexFlags ) : string {
54
+ let result = '' ;
55
+ if ( flags . global ) {
56
+ result += 'g' ;
57
+ }
58
+ if ( flags . ignoreCase ) {
59
+ result += 'i' ;
60
+ }
61
+ if ( flags . multiline ) {
62
+ result += 'm' ;
63
+ }
64
+ if ( flags . hasIndices ) {
65
+ result += 'd' ;
66
+ }
67
+ if ( flags . sticky ) {
68
+ result += 'y' ;
69
+ }
70
+
71
+ return result ;
72
+ }
0 commit comments