-
Notifications
You must be signed in to change notification settings - Fork 2
Regular Expression Matching
Conan edited this page Apr 26, 2022
·
5 revisions
import { match, when } from 'match-iz'
match('hello, world!')(
when(/world/, fullRegExpMatchArray => {
return fullRegExpMatchArray
})
)
// [ 'world', index: 7, input: 'hello, world!', groups: undefined ]
match({ text: 'hello, world!' })(
when({ text: /world/ }, haystack => {
return haystack
})
)
// { text: 'hello, world!' }
-
Passing a
RegExp
literal towhen
will pass the match-array as the first argument tohandler
(if it's a function). -
Using a
RegExp
on an object-prop passes thevalue
frommatch()
, as usual.
If specified, capture groups are extracted automatically from regular-expressions (with the second argument of the when
-handler being the full-match if you need it):
import { match, when, otherwise } from 'match-iz'
match('1 + 2')(
when(
/(?<left>\d+) \+ (?<right>\d+)/,
({ left, right }, fullRegExpMatchArray) => {
return add(left, right)
}
),
when(/no capture groups/, fullRegExpMatchArray => {
return 'so we get the full match array only'
}),
otherwise("I couldn't parse that!")
)
// 3
match-iz
🔥 | on npm | docs home | top of page