我希望得到所有匹配正则表达式。使用Javascript

时间:2017-03-14 02:06:30

标签: javascript regex match combinations

我很抱歉我的英语。

var r=/([a-z]*)[a]{1}([a-z]*)/igm;
var s="araba";

我需要的结果,

a raba index:0
ar a ba index:2
arab a index:4

我怎么能用regexp做到这一点?

2 个答案:

答案 0 :(得分:1)

单个正则表达式调用将无法进行,因为正则表达式在匹配某些内容后无法返回。你必须制作一个正则表达式来寻找你想要的字符集(在你的例子[a]中)并在每次匹配时停止,生成一个新结果并将其推入一个数组(或直接使用它)。 RegExp.prototype.exec需要像这样:



function mySplit(str, charList) {
    // regex will match any character provided in the charList string (no need for {1} as it is the default)
    var regex = new RegExp("[" + charList + "]", "g");
    // the result array, will contain object indecating where the match was found and the parts
    var result = [];
    
    // before starting, execute the regex on the string str
    regex.exec(str);
    // using do-while to guarantee that there will be at least one result in the result array
    do {
        // the index of this match
        var index = regex.lastIndex - 1;
        
        // the result object for this match
        var r = {
            index: index,              // the index
            parts: []                  // the parts (for example "a", "raba" ...)
        };
        
        var p;
        // PREFIX PART
        p = str.substr(0, index);      // get the prefix
        if(p.length) r.parts.push(p);  // if not empty push it
        // THE CHARACTER
        p = str.substr(index, 1);      // get it
        if(p.length) r.parts.push(p);  // if not empty push it (this is could be empty if nothing is matched)
        // POSTFIX PART
        p = str.substr(index + 1);     // get it
        if(p.length) r.parts.push(p);  // push it if not empty
        
        result.push(r);                // push the object r as a result
    } while(regex.exec(str));
    
    return result;
}

console.log(mySplit("araba", "a"));




注意: mySplit的第二个参数可以包含您想要的字母数。例如mySplit("araba", "ab");将返回此信息:

[
    {
        "index": 0,
        "parts": [
            "a",
            "raba"
        ]
    },
    {
        "index": 2,
        "parts": [
            "ar",
            "a",
            "ba"
        ]
    },
    {
        "index": 3,
        "parts": [
            "ara",
            "b",
            "a"
        ]
    },
    {
        "index": 4,
        "parts": [
            "arab",
            "a"
        ]
    }
]

答案 1 :(得分:1)

谢谢İbrahim:) 我的扩展解决方案:

String.prototype.matchAllCombinations=function(regex,includeIndex,constGroups){
	var str=this;
	var includeIndex=includeIndex||false;
	var constGroups=constGroups||[];
	var newRegex;
	if(constGroups.length==0){
		var groups=regex.source.split(new RegExp('([(]{1}[^()]+[)]{1})','g'));
		var newSource='';
		for(var el,it=1,lim=groups.length-1;it<lim;it++){
			el=groups[it];
			if(el.charAt(0)!='('){
				newSource+='('+el+')';
				constGroups.push(it-1);
			}else{
				newSource+=el;
			}
		}
		newRegex=new RegExp(newSource,'');
	}else{
		newRegex=regex;
	}
	var testStr=str;
	var combinations=new Array();
	var matches=new Array();
	var combination=new Array();
	var end=new String();
	var k=new Number();
	var constValues=new Array();
	var itCount=new Number();
	var lastTestStr=new String();
	while((matches=testStr.match(newRegex))!=null){
		k=2;
		correct=true;
		combination=new Array();
		combination=matches.slice(1,matches.length);
		if(combination[combination.length-1]!=""){
			k=1;
		}
		combination[combination.length-k]+=end;
		end=combination[combination.length-k];
		if(itCount==0){
			for(var it=0;it<constGroups.length;it++){
				constValues.push(combination[constGroups[it]]);
			}
		}
		testStr=combination.slice(0,combination.length-k).join('');
		if(lastTestStr==testStr){
			combinations=[];
			break;
		}
		for(var it=0;it<constGroups.length;it++){
			correct&=(combination[constGroups[it]].length==constValues[it].length);
		}
		if(correct){
			if(includeIndex){
				combination["indexes"]=new Array();
				for(var it=0;it<constGroups.length;it++){
					combination["indexes"].push(combination.slice(0,constGroups[it]).join('').length);
				}
			}
			combinations.push(combination);
		}
		lastTestStr=testStr;
		itCount++;
	}
	return combinations;
}
console.log('araba'.matchAllCombinations(new RegExp('([a-z]*)[a]{1}([a-z]*)'),true));
console.log('araba'.matchAllCombinations(new RegExp('([a-z]*)[a]{1}([a-z]*)[a]{1}([a-z]*)'),true));
console.log('araba'.matchAllCombinations(new RegExp('([a-z]*)[a]{1}([a-z]*)[a]{1}([a-z]*)[a]{1}([a-z]*)'),true));
console.log('araba'.matchAllCombinations(new RegExp('([a-z]*)[a]{1}([a-z]*)[a]{1}([a-z]*)[a]{1}([a-z]*)[a]{1}([a-z]*)'),true));
console.log('araba'.matchAllCombinations(new RegExp('([a-z]*)[p]{1}([a-z]*)'),true));
console.log('erebe'.matchAllCombinations(new RegExp('([a-z]*)([a]{1}|[e]{1})([a-z]*)'),true,[1]));