gpt4 book ai didi

javascript - 如何通过不重写相同的捕获组来简化正则表达式?

转载 作者:行者123 更新时间:2023-12-01 01:13:35 25 4
gpt4 key购买 nike

输入文字:

周一至周五上午 6:00 至晚上 8:00

周六至周日上午 6:30 至晚上 8:00

我需要匹配粗体文本,因此以下正则表达式:

(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday) (to) (Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)

如何通过避免重写 (Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday) 捕获组两次来简化正则表达式?

最佳答案

您可以定义一个字符串片段替换,然后重用它:

var input = "Monday to Friday 6:00 a.m. to 8:00 p.m.";
var alt = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)";
var re = new RegExp("^" + alt + " (to) " + alt + ".*$");
if (re.test(input)) {
console.log("valid");
}
else {
console.log("invalid");
}

关于javascript - 如何通过不重写相同的捕获组来简化正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54956052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com