正则表达式计算下划线数量

4

如何通过正则表达式计算和查找下划线,如果下划线数量连续大于2个且小于4个,执行某些操作,如果下划线数量大于4个,执行其他操作

$('div').text(function(i, text) {
  var regex2 = /_{2,4}/g;
  var regex4 = /_{4,999}/g;
  //var regexLength = text.match(regex).length;

  if (regex2.test(text)) {
    return text.replace(regex2, '،');
  } else if (regex4.test(text)) {
    return text.replace(regex4, '');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________
</div>

我想做的是,查找两个以上连续的下划线并将其替换为 逗号,如果下划线连续出现四次以上,则将其替换为空白。

现在:

<div>
  Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________
</div>

目标:

<div>
  Blah_Blah _ BlahBlah , test , Blah
</div>

问题:

第二个regex表达式(超过四个下划线)的效果不如预期。

JSFiddle


2
_{2,4} 匹配 2、3 或 4 个下划线。 _{4,999} 匹配 4 个到 999 个下划线。你的模式重叠。 - Wiktor Stribiżew
1
首先检查 4,999,然后在 else 语句中检查 2,4 - anubhava
1
@anubhava 谢谢,这帮了我一个大忙。 - Pedram
1
好的,所以它是https://jsfiddle.net/ckrk0o95/2/。 - Wiktor Stribiżew
1
@WiktorStribiżew 目前问题是 underscore,但我相信将来我需要添加更多。因为这被用作用户输入的清理工具。我认为两者都很有效。 - Pedram
显示剩余4条评论
2个回答

3

以下是如何在单个正则表达式中完成此操作,而无需多个正则表达式 testreplace 调用:

var str = 'Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________'
var r = str.replace(/_{2,}/g, function(m) { return (m.length>4 ? '' : ',') })
console.log(r)

//=> Blah_Blah _ BlahBlah , test , Blah 


0
const string = "Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________";
const count_underscore_occurrence = (string.match(/_/g) || []).length;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接