简体   繁体   中英

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

I have an interval information like "Sat 8-11, Sat 11-18" and I want to check if the second hour in the first interval (11) equals to the first hour in the second interval (11), then merge this two hours into one "Sat 8-18". That would be great if anyone gives me a hint.

You can do this with a replace using back references:

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

The solution using String.prototype.match() function with specific regex pattern:

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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