javascript reg exp

时间:2016-11-30 09:44:34

标签: javascript regex

即时通讯新学生......目前我正试图找出如何获得此regExp,对不起,首先很难解释。

我想要regExp:

ABCD //which given true in exact sequence

input : AOOBCOODOO or ACCCBCOODOO
output: aOObcOOdOO  or aCCCbcOOdOO    //A,B,C,D in order get lower-cased

input : AYYBTTCDDD , output : aYYbTTcdD ;
input : ASRBB // return false no 'C' 'D'
input : AABBCCDD , output : aAbBcCdD 

将返回true,小写为' A' ' B' ' C' ' d' ,和第二个字母表同样不会被改变

//the A,B,C,D change to lower case.

这是我尝试过的:

    var rE = /A.*[B].*[C].*[D]/g;   //so i can get exact-order for regex 
//which  are A >> B >> C >> D

所以我想返回单词,但exact alphabet会有所不同(小写);

1 个答案:

答案 0 :(得分:0)

我认为这就是你需要的



function extract(input, words) {
  // Any array or string "words" argument is acceptable
  if(typeof words === 'string') {
    // Lets convert words to array if it is single string
    words = words.split('');
  }
  
  // We only accept string inputs and array words
  if(typeof input !== 'string' || !Array.isArray(words)) {
    throw new SyntaxError('input not string or words not in expected format');
  }
  
  // Lets create a regex which extracts all words and others
  var reg = new RegExp(
    '^(.*?)' + 
    words.map(w => `(${w})`).join('(.*?)') +
    '(.*)$', 
    'i'
  );
  
  // If input matches then let replace it, otherwise it will return false
  return reg.test(input) && input.replace(reg, function() {
    // first argument is $0 (matched input)
    // last couple arguments are index and input
    
    // other arguments are groups
    // Even indexed groups are our non matched parts
    var args = Array.prototype.slice.call(arguments, 1, arguments.length - 2);
    
    return args.map((a, idx) => ((idx % 2) && a.toLowerCase()) || a)
      .join('');
  });
}
                                          
console.log(extract('AABBBBBBCCDD', 'ABCD'))
console.log(extract('ASRBB', 'ABCD'))
console.log(extract('aAAaaBBbbbbBBcccDDddd', 'ABCD'))
console.log(extract('HOWHJJHJHHABOUTKKHHOTHERS', ['HOW', 'ABOUT', 'OTHERS']));