【问题标题】:I want to get all matches with regex. Javascript我想用正则表达式获得所有匹配。 Javascript
【发布时间】:2017-03-14 02:06:30
【问题描述】:

对不起我的英语。

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

我怎样才能用正则表达式做到这一点?

【问题讨论】:

  • 你想要这个只是为了角色a?或者这可以与其他角色一起应用?
  • 是的,我将把它括在所有声明的括号中。例如,s="şelaleler"。 r=/([a-z]+)[l][1}[e]{1}([a-z]+)/;结果= şela le ler, şelale le r

标签: javascript regex match combinations


【解决方案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"
        ]
    }
]

【讨论】:

    【解决方案2】:

    谢谢伊布拉欣 :) 我的扩展解决方案:

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

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 2021-09-23
      • 2011-11-29
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多