2016-11-30 60 views
-2

即時新學生...現在我試圖找出如何得到這個regExp,對不起,第一,很難解釋。javascript reg exp

我想對正則表達式:

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',第二個字母,其同樣不會改變

​​

這是我曾嘗試:

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

所以我要回報的話,但exact alphabet會不同(小寫);

+0

'String.toLowerCase()'是不是不夠好? – nicovank

+0

@nicovank和一切都變得小寫呢?我只是想要確切的字母表,這就是爲什麼使用正則表達式? –

+0

您可能需要編寫某種解析器 – TheLostMind

回答

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']));