【发布时间】:2022-01-19 06:36:57
【问题描述】:
我想通过字符的位置找到一个单词:
const wordlist = ['xenon', 'rewax', 'roger', 'bob', 'xylophone']
而且,要找到木琴,我将拥有:
const charSlotPairs = [{char: "x", slot: 0}, {char: "y", slot: 1}];
所以我正在动态构建正则表达式(^.{0}[x])(^.{1}[y])
但我认为这个正则表达式是错误的......如何根据字符串中字符的位置找到匹配项?
function (charSlotPairs){
let regexStr = ""
charSlotPairs.forEach( pair => {
regexStr += `(^.{${pair.slot}}[${pair.char}])`
})
const regex = new RegExp(`${regexStr}\\w`, 'g')
return this.filter( word => !word.match(regex) )
}
【问题讨论】:
-
let regexStr = "^"然后regexStr += `(?=.{${pair.slot}}${pair.char.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')})。你真的认为在这里使用正则表达式值得(ab)吗? -
谢谢,原来的正则表达式很简单...
标签: javascript string