| 1 | const REGEX_SPECIAL = /[\\^$.*+?()[\]{}|]/g
|
|---|
| 2 | const REGEX_HAS_SPECIAL = RegExp(REGEX_SPECIAL.source)
|
|---|
| 3 |
|
|---|
| 4 | /**
|
|---|
| 5 | * @param {string|RegExp|Array<string|RegExp>} source
|
|---|
| 6 | */
|
|---|
| 7 | function toSource(source) {
|
|---|
| 8 | source = Array.isArray(source) ? source : [source]
|
|---|
| 9 |
|
|---|
| 10 | source = source.map((item) => (item instanceof RegExp ? item.source : item))
|
|---|
| 11 |
|
|---|
| 12 | return source.join('')
|
|---|
| 13 | }
|
|---|
| 14 |
|
|---|
| 15 | /**
|
|---|
| 16 | * @param {string|RegExp|Array<string|RegExp>} source
|
|---|
| 17 | */
|
|---|
| 18 | export function pattern(source) {
|
|---|
| 19 | return new RegExp(toSource(source), 'g')
|
|---|
| 20 | }
|
|---|
| 21 |
|
|---|
| 22 | /**
|
|---|
| 23 | * @param {string|RegExp|Array<string|RegExp>} source
|
|---|
| 24 | */
|
|---|
| 25 | export function withoutCapturing(source) {
|
|---|
| 26 | return new RegExp(`(?:${toSource(source)})`, 'g')
|
|---|
| 27 | }
|
|---|
| 28 |
|
|---|
| 29 | /**
|
|---|
| 30 | * @param {Array<string|RegExp>} sources
|
|---|
| 31 | */
|
|---|
| 32 | export function any(sources) {
|
|---|
| 33 | return `(?:${sources.map(toSource).join('|')})`
|
|---|
| 34 | }
|
|---|
| 35 |
|
|---|
| 36 | /**
|
|---|
| 37 | * @param {string|RegExp} source
|
|---|
| 38 | */
|
|---|
| 39 | export function optional(source) {
|
|---|
| 40 | return `(?:${toSource(source)})?`
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | /**
|
|---|
| 44 | * @param {string|RegExp|Array<string|RegExp>} source
|
|---|
| 45 | */
|
|---|
| 46 | export function zeroOrMore(source) {
|
|---|
| 47 | return `(?:${toSource(source)})*`
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | /**
|
|---|
| 51 | * Generate a RegExp that matches balanced brackets for a given depth
|
|---|
| 52 | * We have to specify a depth because JS doesn't support recursive groups using ?R
|
|---|
| 53 | *
|
|---|
| 54 | * Based on https://stackoverflow.com/questions/17759004/how-to-match-string-within-parentheses-nested-in-java/17759264#17759264
|
|---|
| 55 | *
|
|---|
| 56 | * @param {string|RegExp|Array<string|RegExp>} source
|
|---|
| 57 | */
|
|---|
| 58 | export function nestedBrackets(open, close, depth = 1) {
|
|---|
| 59 | return withoutCapturing([
|
|---|
| 60 | escape(open),
|
|---|
| 61 | /[^\s]*/,
|
|---|
| 62 | depth === 1
|
|---|
| 63 | ? `[^${escape(open)}${escape(close)}\s]*`
|
|---|
| 64 | : any([`[^${escape(open)}${escape(close)}\s]*`, nestedBrackets(open, close, depth - 1)]),
|
|---|
| 65 | /[^\s]*/,
|
|---|
| 66 | escape(close),
|
|---|
| 67 | ])
|
|---|
| 68 | }
|
|---|
| 69 |
|
|---|
| 70 | export function escape(string) {
|
|---|
| 71 | return string && REGEX_HAS_SPECIAL.test(string)
|
|---|
| 72 | ? string.replace(REGEX_SPECIAL, '\\$&')
|
|---|
| 73 | : string || ''
|
|---|
| 74 | }
|
|---|