javascript 异步正则表达式迭代器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 异步正则表达式迭代器相关的知识,希望对你有一定的参考价值。

/**
 * Generator function to produce an iterable result of regex matches that can be
 * asyncronously processed and converted
 */
function* findMatchesIterator(matcher, stringToSearch) {
  let result
  let matchFound
  while (matchFound !== null) {
    matchFound = result = matcher.exec(stringToSearch)
    if (matchFound) {
      yield result
    }
  }
}

/**
 * Compose an async replacer function for a specific match
 */
 export const matchesReplacer = (tokenPattern, matchProcesser) => async (
  stringToReplace
) => {
  const matches = []
  const i = findMatchesIterator(tokenPattern, stringToReplace)
  let currentMatch = i.next()
  while (!currentMatch.done) {
    try {
      const matchToReplace = await matchProcesser(currentMatch.value)
      if (matchToReplace) {
        matches.push(matchToReplace)
      }
    } catch (err) {
      logger.error(`Error matching ${tokenPattern} - ${err}`)
      return ''
    }
    currentMatch = i.next()
  }
  let newString = stringToReplace
  matches.forEach(r => {
    newString = newString.replace(r.matchedString, r.replaceWith)
  })
  return newString
}

以上是关于javascript 异步正则表达式迭代器的主要内容,如果未能解决你的问题,请参考以下文章

第 4 天 迭代器生成器装饰器正则表达式

Python装饰器迭代器&生成器re正则表达式字符串格式化

day4迭代器&生成器&正则表达式

Python装饰器迭代器生成器re正则表达式字符串格式

Python装饰器迭代器&生成器re正则表达式字符串格式化

Python 迭代器&生成器,装饰器,递归,算法基础:二分查找二维数组转换,正则表达式,作业:计算器开发