1
0
Fork 0
peertube/server/core/helpers/regexp.ts
Chocobozzz 29329d6c45 Implement auto tag on comments and videos
* Comments and videos can be automatically tagged using core rules or
   watched word lists
 * These tags can be used to automatically filter videos and comments
 * Introduce a new video comment policy where comments must be approved
   first
 * Comments may have to be approved if the user auto block them using
   core rules or watched word lists
 * Implement FEP-5624 to federate reply control policies
2024-05-29 15:03:14 +02:00

36 lines
1,015 B
TypeScript

// Thanks to https://regex101.com
export function regexpCapture (str: string, regex: RegExp, maxIterations = 100) {
const result: RegExpExecArray[] = []
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
}
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, '\\$&')
}