Skip to content

Commit 5d497a1

Browse files
committed
feat(regex): add rx_to_str func, add support for nesting rx in templates
1 parent 5aefc55 commit 5d497a1

File tree

2 files changed

+47
-9
lines changed

2 files changed

+47
-9
lines changed

src/regex.fnk

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
{new} = import '@fink/js-interop/reflect.fnk'
1+
{new, is_instance} = import '@fink/js-interop/reflect.fnk'
22
{RegExp} = import '@fink/js-interop/globals.fnk'
33

44
{raw} = import './str.fnk'
@@ -8,6 +8,16 @@ regex = fn pattern, flags='':
88
new RegExp, pattern, 'u${flags}'
99

1010

11+
12+
rx_to_str = fn value:
13+
value.source
14+
15+
16+
17+
is_rx = fn value:
18+
is_instance value, RegExp
19+
20+
1121
---
1222
Create a regex for the given raw string.
1323

@@ -31,7 +41,13 @@ rx = fn strings, ...exprs:
3141
replace_all ?, ingorables, ''
3242
replace_all ?, esc, '$1$3'
3343

34-
regex raw {raw: parts}, ...exprs
44+
45+
regex raw {raw: parts}, ... exprs | map expr:
46+
match expr:
47+
is_rx ?:
48+
expr.source
49+
else:
50+
expr
3551

3652

3753
match_all = fn str, rx:
@@ -56,3 +72,6 @@ replace_all = fn str, rx, replacement:
5672

5773

5874
matches = fn str, rx: rx.test str
75+
76+
77+

src/regex.test.fnk

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{describe, it, expect, to_equal} = import '@fink/jest/test.fnk'
22

3-
{matches, match_all, find_index, split, replace_all, replace, rx, regex} = import './regex.fnk'
3+
{matches, match_all, find_index, split, replace_all, replace, rx, is_rx, rx_to_str} = import './regex.fnk'
44

55

6-
describe 'regex', fn:
6+
describe rx, fn:
77
it 'matches single', fn:
88
expect
99
matches 'foobar', rx'.+oo.+'
@@ -52,7 +52,7 @@ describe 'regex', fn:
5252

5353

5454

55-
describe 'string templates', fn:
55+
describe 'rx expressions', fn:
5656
it 'creates a regex', fn:
5757
expect
5858
rx'\(.+?\)(foo{${1},${4}})'
@@ -71,16 +71,35 @@ describe 'string templates', fn:
7171

7272
it 'handles escaping', fn:
7373
expect
74-
rx'
74+
rx_to_str rx'
7575
\'\"`
7676
foo \# bar
7777
\${2}
7878
\\*
7979
'
80-
to_equal regex '\'"`foo # bar\\\${2}\\\\*'
80+
to_equal '\'"`foo # bar\\\${2}\\\\*'
8181

8282

8383
it 'handles spaces', fn:
8484
expect
85-
rx'[ ]{3}'
86-
to_equal regex '[ ]{3}'
85+
rx_to_str rx'[ ]{3}'
86+
to_equal '[ ]{3}'
87+
88+
89+
it 'handles nesting', fn:
90+
expect
91+
rx_to_str rx'^.+?${ rx'foo.+' }$'
92+
to_equal '^.+?foo.+$'
93+
94+
95+
96+
describe is_rx, fn:
97+
it 'asserts if value is regex', fn:
98+
expect
99+
is_rx rx'foo'
100+
to_equal true
101+
102+
expect
103+
is_rx '/foo/'
104+
to_equal false
105+

0 commit comments

Comments
 (0)