【问题标题】:Replace Letters with Position in Alphabet - Regex用字母表中的位置替换字母 - 正则表达式
【发布时间】:2016-11-09 20:15:53
【问题描述】:

这个挑战的描述是取一个字符串并将字母替换为字母表中从 1-index 开始的字母位置。要求您跳过所有非字符,包括空格。

function alphabetPosition(text) {
  var result = [];
  var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
    "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
    "w", "x", "y", "z"]
  text = text.replace(/\W*\d+/g, '').toLowerCase().split('');
  for (var i = 0; i < text.length; i++) 
    result.push(alphabet.indexOf(text[i]) + 1);
  return result.join(' ');
}

我的问题是当涉及到随机测试时,输入将包含数字和非单词字符,但正则表达式无法识别它。输入为n8_ovuu&amp;,输出/错误为Expected: '14 15 22 21 21', instead got: '14 0 15 22 21 21 0'

问题在于正则表达式,但我无法弄清楚。如果您有任何想法,我将不胜感激!

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    在循环中添加条件:

    替换:

    for (var i = 0; i < text.length; i++) 
      result.push(alphabet.indexOf(text[i]) + 1);
    

    与:

    for (var i = 0; i < text.length; i++) {
      var j = alphabet.indexOf(text[i]) + 1;
      if (j) result.push(j);
    }
    

    请注意,您可以将字母表定义为字符串而不是数组,而无需对上述循环进行任何更改:

    var alphabet = 'abcdefghijklmnopqrstuvwxyz';
    

    函数式编程解决方案 - 没有 RegEx

    这是一个 ES6 代码解决方案,它在一个 return 语句中将一个方法链接到一个方法以返回结果:

    function alphabetPosition(text) {
      return text.toLowerCase().split('')
            .filter( c => c >= 'a' & c <= 'z' )
            .map( c => c.charCodeAt(0) - 'a'.charCodeAt(0) + 1)
            .join(' ');
    }
    
    console.log(alphabetPosition('n8_ovuu&'));

    函数式编程解决方案 - 使用 RegEx

    function alphabetPosition(text) {
      return text.toLowerCase().replace(/[^a-z]/g, '')
            .replace(/./g, ([c]) => ' ' + (c.charCodeAt(0) - 'a'.charCodeAt(0) + 1))
            .substr(1);
    }
    
    console.log(alphabetPosition('n8_ovuu&'));

    【讨论】:

    • 这行得通,这也让我摆脱了正则表达式,这对我来说是一种解脱!
    • 确实,您还可以简化字母表变量。它可以只是一个字符串,因为它支持indexOf,就像一个数组一样。
    • 为了好玩,我还添加了一个完全不同的解决方案。
    【解决方案2】:

    由于某些字符(例如 _&amp;)与字母表不匹配,您得到了零。当.indexOf() 找不到匹配项时,它返回-1。然后,您会将 + 1 添加到其中,使其为零。

    您可以将这些字符添加到字母表中,也可以通过简单地添加 if 子句来忽略这些字符。

    for (var i = 0; i < text.length; i++) {
        var index = alphabet.indexOf(text[i]);
        if (index > -1) {
            result.push(index + 1);
        }
    }
    

    要告诉您的正则表达式过滤非字母字符,请将 \W 替换为显式反转字符范围 [^a-zA-Z]

    console.log("abc_def".replace(/[^a-zA-Z]/, ''));

    【讨论】:

    • 我明白了,我正试图弄清楚如何让正则表达式识别那些使用text.replace + 正则表达式替换它们的非单词字符。
    • 请更新您的问题并澄清这是不工作的正则表达式。我已经更新了我的答案以解释如何修复正则表达式。
    • 已更新,使其在标题和正文中。感谢您澄清正则表达式!非常感谢!
    【解决方案3】:

    这很有效,而且非常简洁:

    const data = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"£$%^&*()';
    
    const result = data.toLowerCase().match(/[a-z]/g).map(c => c.charCodeAt(0) - 96).join(' ');
    
    console.log(result);

    【讨论】:

      【解决方案4】:

      您可以使用对象作为字母的索引。如果没有找到,就取一个默认值。

      function alphabetPosition(text) {
          var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
              object = {};
      
          alphabet.forEach(function (a, i) {
              object[a] = i + 1;
          });
          return text.replace(/\W*\d+/g, '').toLowerCase().split('').map(function (a) {
              return object[a] || 0;
          }).join(' ');
      }
      
      console.log(alphabetPosition('n8_ovuu&'));

      【讨论】:

        【解决方案5】:

        嘿,这对我有用。

        const alphabetPosition = (text) => {
            // First isolate the characters in the string using split method, and then map them.
            const result = text.split('').map(a => parseInt(a, 36) - 9)
                .filter(a => a >= +1).join(' ')
        
            console.log(result)
          }
        
        alphabetPosition(text)
        

        【讨论】:

          【解决方案6】:
          import string
          
          def alphabet_position(text):
            text = text.lower
            result = ""
            for x in text():
               if x.isalpha():
                  result = result + str(string.ascii_lowercase.index(x) + 1) + " "
              else:
                  pass
            result = result.strip()
            return result
          

          【讨论】:

          • 不要直接粘贴代码,请稍作说明后再粘贴。
          猜你喜欢
          • 2020-01-02
          • 2022-01-10
          • 1970-01-01
          • 2014-06-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-09
          相关资源
          最近更新 更多