Regex - Match up until there's an equal amount of 2 specific characters

廉价感情. 提交于 2021-02-04 19:50:11

问题


For example if I have the following sentence:

a cat bit a dog on the butt before running away

If the 2 characters I want to use are 'a' and 'b' then I want to match up until the point where there are equal amounts of 'a' and 'b' like the following:

a cat bit a dog on the butt b

In the above case, the sentence has 5 a's and 3 b's. I want to much up to the point where I have 3 a's and 3 b's.

Thank you for the help.


回答1:


var a = 0,
    b = 0;
var result = 0;
var patten = /./g;
for (;patten.exec("a cat bit a dog on the butt before running away") != null;) {
    if (RegExp['$&'] == "a") {
        a++;
		if (a == b) {
			result = patten.lastIndex;
        }
    }
    if (RegExp['$&'] == "b") {
        b++;
        if (a == b) {
            result = patten.lastIndex;
        }
    }
}
console.log("1~" + result);
console.log("a cat bit a dog on the butt before running away".slice(0,result));
by the way, 朕也会功夫。


回答2:


It's not possible.

an bn is not regular, thus matching with a regular expression is mathematically not possible, even with enhanced regular expressions.

You can use the following function to get the range which doesn't use a regular expression:

var input = "a cat bit a dog on the butt b";
console.log(getRange(input, "a", "b"));

function getRange(input, char1, char2){
  var indexStart = -1;
  var count1 = 0, count2 = 0;
  
  for(var i = 0; i < input.length; i++){
    var char = input[i];
    switch(char){
      case char1:
        count1 += 1; break
      case char2:
        count2 += 1; break;
    }
    if(char == char1 || char == char2){
      if(indexStart == -1)
        indexStart = i;

      if(count1 == count2)
        return [indexStart, i];
    }
  }
  
  return [-1, -1];
}


来源:https://stackoverflow.com/questions/47644164/regex-match-up-until-theres-an-equal-amount-of-2-specific-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!