繁体   English   中英

如何在匹配函数中检查正则表达式中的两个组是否相等

[英]how can I check two groups in a regular expression are equal inside the match function

我有一个间隔信息,例如“ Sat 8-11,Sat 11-18”,我想检查第一个间隔(11)中的第二个小时是否等于第二个间隔(11)中的第一个小时,然后将这两个间隔合并一小时进入“ 8月8日星期六”。 如果有人给我提示,那将很棒。

您可以使用回溯引用进行replace

 var s = "Sat 8-11, Sat 11-18"; s = s.replace(/([az]+) (\\d+)-(\\d+), \\1 \\3-/i, "$1 $2-"); console.log(s); 

使用String.prototype.match()函数和特定正则表达式模式的解决方案:

 var s = "Sat 8-11, Sat 11-18", r = s.match(/([AZ][az]+) (\\d{1,2})-(\\d{1,2}), \\1 (\\d{1,2})-(\\d{1,2})/); // if the input string matches the pattern and the second hour // in the first interval equals to the first hour in the second interval if (r.length == 6 && r[3] == r[4]) { s = r[1] +' '+ r[2] +'-'+ r[5]; } console.log(s) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM