【问题标题】:How to match the Nth char in a string in javascript?如何在javascript中匹配字符串中的第N个字符?
【发布时间】: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


【解决方案1】:

这是我解决它的方法,而不是使用正则表达式:

function (charSlotPairs){
  return !!charSlotPairs.find(pair => 
    a.every( word => 
      word.charAt(pair.slot) == pair.char)
    )
}

【讨论】:

  • 谢谢你这很接近......但 .find() 只返回第一个。我最终使用了 .every()。
【解决方案2】:

您的查询只能使用循环来解决。

const wordlist = ['xenon', 'rewax', 'roger', 'bob', 'xylophone'];
const charSlotPairs = [{char: "x", slot: 0}, {char: "y", slot: 1}];

let stringFinder = (StrArr, KeyArr) =>
{
    var match = false;  // Indicator Variable 

    // For Iterating a String Array 
    for (var i of StrArr) 
    {
        // For Iterating the Object Array for each Key  
        for (var x of KeyArr) 
        {
            /*
              |If Conditon fails, match will set to false and Loop will Break
              |Otherwise Loop will continue
            */ 
            if (i.charAt(x.slot) != x.char) 
            {
                match = false;
                break;
            }
            else
            {
                match = true;
            }
        }

        /*
          |If the Inner Loop is completed and match is true => Success  
          |If the Inner Loop is completed and match is false => Failed  
        */ 
        if (match) 
        {
            return i;
        }
    }
    return false;
}

console.log(stringFinder(wordlist, charSlotPairs));

【讨论】:

    【解决方案3】:

    我最终过滤了单词列表,然后使用 .every() 确保它们都通过了过滤器

    Array.prototype.findWordsWithLettersInSlots = function (letterSlotPairs){
      if( letterSlotPairs.length === 0 ) return this
      if( Object.keys(letterSlotPairs).length === 0 ) return this
    
      return this.filter( word => {
        return letterSlotPairs.every( (pair) => {
          return word.charAt(pair.slot) === pair.letter 
        })
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多