正则表达式,只抓取每个字母的一个实例

时间:2011-06-14 15:17:31

标签: javascript regex

我有一个段落被分解成一个数组,在句号中分开。我想对index [i]执行一个正则表达式,用index [i]的字符串值所具有的每个字母的一个实例替换它的内容。

因此; index [i]:“这是一个句子”将返回 - >指数[I]: “thisaenc”

我读了this thread。但我不确定这是不是我正在寻找的。

6 个答案:

答案 0 :(得分:2)

不确定如何在正则表达式中执行此操作,但这是一个非常简单的功能,可以在不使用正则表达式的情况下执行此操作:

function charsInString(input) {
    var output='';
    for(var pos=0; pos<input.length; pos++) {
        char=input.charAt(pos).toLowerCase();
        if(output.indexOf(char) == -1 && char != ' ') {output+=char;}
    }
    return output;
}

alert(charsInString('This is a sentence'));

答案 1 :(得分:1)

由于我非常确定使用单个正则表达式无法实现所需,我提供了更通用的解决方案:



// collapseSentences(ary) will collapse each sentence in ary 
// into a string containing its constituent chars
// @param  {Array}  the array of strings to collapse
// @return {Array}  the collapsed sentences
function collapseSentences(ary){
  var result=[];
  ary.forEach(function(line){
    var tmp={};
    line.toLowerCase().split('').forEach(function(c){
        if(c >= 'a' && c <= 'z') {
            tmp[c]++;
        }
    });
    result.push(Object.keys(tmp).join(''));
  });
  return result;
}

哪个应该做你想要的,除了不能保证每个句子中的字符顺序被保留,尽管在大多数情况下它是。

假设:

var index=['This is a sentence','This is a test','this is another test'],
    result=collapseSentences(index);

结果包含:

["thisaenc","thisae", "thisanoer"]

答案 2 :(得分:0)

(\w)(?<!.*?\1)

这会为每个正确的字符生成匹配,但就好像您从右向左阅读一样。 这会找到一个单词字符,然后查看刚刚匹配的字符。

答案 3 :(得分:0)

没关系,我设法:

justC = "";
if (color[i+1].match(/A/g)) {justC += " L_A";}
if (color[i+1].match(/B/g)) {justC += " L_B";}
if (color[i+1].match(/C/g)) {justC += " L_C";}
if (color[i+1].match(/D/g)) {justC += " L_D";}
if (color[i+1].match(/E/g)) {justC += " L_E";}
else {color[i+1] = "L_F";}

这不正是我的问题可能导致相信是我想要的,但打印出来的是我所追求的,用于课堂:<span class="L_A L_C L_E"></span>

答案 4 :(得分:0)

怎么样:

var re = /(.)((.*?)\1)/g;
var str = 'This is a sentence';
x = str.toLowerCase();
x = x.replace(/ /g, '');
while(x.match(re)) {
    x=x.replace(re, '$1$3');
}

答案 5 :(得分:-1)

我不认为这可以在一次性正则表达式中完成。您将需要使用循环。

虽然我的示例不是用您选择的语言编写的,但它似乎没有使用javascript中没有的任何正则表达式功能。

perl -e '$foo="This is a sentence"; while ($foo =~ s/((.).*?)\2/$1/ig)  { print "<$1><$2><$foo>\n"; } print "$foo\n";'

产:

This aenc