【问题标题】:Match only one word for each starting letter每个起始字母只匹配一个单词
【发布时间】:2016-04-05 03:01:14
【问题描述】:

您可以在此处查看我希望如何过滤单词:

string = 'Take all first words for each letter... this is a test';
first_letters = {};

words = string.match(/\w+/g);
words.forEach(function(x){
    var first = x[0].toLowerCase();
    first_letters[first] = (first_letters[first] || x);
});

result = [];
for (var x in first_letters) {
    result.push(first_letters[x]);
}

O.innerHTML = result;
<pre id=O>

我正在尝试仅使用正则表达式来获取上面显示的数组result,我开始尝试首先获取首字母:

result = words.match(/\b(?!\1)(\w)/gi);

但是(?!\1) 并没有像我想象的那样过滤字母。你可以看到here

欢迎任何帮助。谢谢

【问题讨论】:

  • 您好!你想要一个这样的数组 = [T,a,f,w,f,e,t,i,a,t] ?
  • 也许使用 \b\w 获取所有首字母,然后使用 JavaScript 来完成剩下的工作?
  • @I'm_ADR。不,在您的数组a,f,t 中有重复项,我不想要重复项。
  • @Laurel。实际上,我的代码有效,但我试图仅使用正则表达式来获得相同的结果,但我遇到了麻烦;)
  • @WashingtonGuedes 为什么?你知道正则表达式不是万能的吗?

标签: javascript regex


【解决方案1】:

这个正则表达式只会找到唯一的首字母:

r = /\b(\w)(?!.*\b\1)/gi;

这个正则表达式说:

在分词后查找第一个字母,但前提是相同的字母没有在字符串后面的分词后立即出现(否定前瞻)。

string = 'Take all first words for each letter... this is a test';

> string.match(r)
< ["w", "f", "e", "l", "i", "a", "t"]

要为每个唯一的第一个字母查找一个单词:

r = /\b((\w)\w*)(?!.*\b\2)/gi

> string.match(r)
< ["words", "for", "each", "letter", "is", "a", "test"]

正如@karthik manchala 在评论中提到的那样,由于正则表达式的限制,这只会找到以每个字母开头的last 单词。要找到以每个字母开头的第一个单词,您必须反转字符串中的单词:

> string . split(' ') . reverse() . join(' ') . match(r) . reverse()
< ["Take", "all", "first", "words", "each", "letter", "is"]

你的初始正则表达式

/\b(?!\1)(\w)/gi

由于\1 必须引用更早的捕获组,因此无法正常运行。

【讨论】:

  • 我也开启了挑战here ;)
【解决方案2】:

我做到了!

var string = 'Take all first words for each letter... this is a test';

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

function removeSpecials(string) {
  return string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'');
}

function toLowerCase(string) {
  return string.toLowerCase();
}

function getWords(string) {
  return string.split(' ');  
}

function getChar(array) {
  return array.reduce(function(chars, item) {
    if (!chars.contains(item[0])) { chars.push(item[0]) }
     return chars
  }, []);
}

console.log(getChar(getWords(toLowerCase(removeSpecials(string)))))

代码笔:http://codepen.io/anon/pen/QNOypw?editors=0010

【讨论】:

    【解决方案3】:

    请尝试:

    var string = 'Take all first words for each letter... this is a test';
    
    // reverse the input string
    string = string.split(" ").reverse().join(" ");
    var re = /\b((\w)[a-z]*)(?!.*?\b\2)/gi;
    
    var words = [], m;
    while (m = re.exec(string)) {
        words.push(m[0])
    }
    
    document.write(words.reverse().join(","));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多