allowedWordOrLetterToRegExpGroup
convert a comma separated list of letters and words into a regexp group that will match any of the allowed letters or words once.
by lid0
JavaScript
/**
convert a comma separated list of letters and words into a regexp group
that will match any of the allowed letters or words once.
for a given input
"a,b,c,abc"
return a regexp group
(abc|[abc]{1})
*/
function allowedWordOrLetterToRegExpGroup(str_in,subgroup) {
function escape(i) { //escape any none alphanumeric
return i.replace(/[^A-z0-9,]/g, function (match) {
return ("\\" + match); //add escape char to match
});
}
//str_in = str_in.replace(/[^A-z0-9,]/g,""); //remove none alphanumeric
//str_in = str_in.replace(/[^A-z0-9,]/g,function(match,$1){return ("\\" + match);}); //escape none alphanumeric
var items = str_in.split(",");
var letter = "";
var word = [];
for (var s in items) {
if (items[s].length <= 1) {
letter += escape(items[s]);
//letter+=items[s];
} else {
word.push(escape(items[s]));
//word.push(items[s]);
}
}
if(subgroup){ //add subgroup to words and letter match
lt ="";
if (letter.length > 0) lt = ")|([" + letter + "]{1})";
return "((" + word.join("|") + lt+ ")";
} else {
if (letter.length > 0) word.push("[" + letter + "]{1}"); //push letter to word array so we can join with |
return "(" + word.join("|") + ")";
}
}
r = allowedWordOrLetterToRegExpGroup("hour,minute,day,h,m,d");
console.log(r);
r = allowedWordOrLetterToRegExpGroup("hour,minute,day,h,m,d",true);
console.log(r);