ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

33 lines
852 B

  1. // Thanks to https://regex101.com
  2. export function regexpCapture (str: string, regex: RegExp, maxIterations = 100) {
  3. const result: RegExpExecArray[] = []
  4. let m: RegExpExecArray
  5. let i = 0
  6. while ((m = regex.exec(str)) !== null && i < maxIterations) {
  7. // This is necessary to avoid infinite loops with zero-width matches
  8. if (m.index === regex.lastIndex) {
  9. regex.lastIndex++
  10. }
  11. result.push(m)
  12. i++
  13. }
  14. return result
  15. }
  16. export function wordsToRegExp (words: string[]) {
  17. if (words.length === 0) throw new Error('Need words with at least one element')
  18. const innerRegex = words
  19. .map(word => escapeForRegex(word.trim()))
  20. .join('|')
  21. return new RegExp(`(?:\\P{L}|^)(?:${innerRegex})(?=\\P{L}|$)`, 'iu')
  22. }
  23. export function escapeForRegex (value: string) {
  24. return value.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
  25. }