2019-01-04 01:56:20 -06:00
|
|
|
// Thanks to https://regex101.com
|
2024-03-29 08:25:03 -05:00
|
|
|
export function regexpCapture (str: string, regex: RegExp, maxIterations = 100) {
|
2020-01-31 09:56:52 -06:00
|
|
|
const result: RegExpExecArray[] = []
|
2019-01-04 01:56:20 -06:00
|
|
|
let m: RegExpExecArray
|
|
|
|
let i = 0
|
|
|
|
|
|
|
|
while ((m = regex.exec(str)) !== null && i < maxIterations) {
|
|
|
|
// This is necessary to avoid infinite loops with zero-width matches
|
|
|
|
if (m.index === regex.lastIndex) {
|
|
|
|
regex.lastIndex++
|
|
|
|
}
|
|
|
|
|
|
|
|
result.push(m)
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2024-03-29 08:25:03 -05:00
|
|
|
export function wordsToRegExp (words: string[]) {
|
|
|
|
if (words.length === 0) throw new Error('Need words with at least one element')
|
|
|
|
|
|
|
|
const innerRegex = words
|
|
|
|
.map(word => escapeForRegex(word.trim()))
|
|
|
|
.join('|')
|
|
|
|
|
|
|
|
return new RegExp(`(?:\\P{L}|^)(?:${innerRegex})(?=\\P{L}|$)`, 'iu')
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Private
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
function escapeForRegex (value: string) {
|
|
|
|
return value.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
|
2019-01-04 01:56:20 -06:00
|
|
|
}
|