如何利用正则表达式优化JavaScript匹配结果的拼接处理?
用正则重构匹配结果格式化逻辑
你可以通过两次针对性的正则替换,或者一个更通用的正则替换函数来解决多余to的问题,不用写if判断:
方案一:两次精准正则替换
针对你遇到的两种场景,直接替换掉位置不对的to:
// 第一种匹配数组 let matches1 = ['10 am', '5 pm', 'by appointment only']; let result1 = matches1.join(' to ') .replace(/(^[^0-9]+)\s+to\s+/, '$1 ') // 处理开头非时间内容后的多余to .replace(/\s+to\s+([^0-9]+$)/, ' $1'); // 处理末尾非时间内容前的多余to // 输出:'10 am to 5 pm by appointment only' // 第二种匹配数组 let matches2 = ['By Appointment :', '10 am', '8 pm']; let result2 = matches2.join(' to ') .replace(/(^[^0-9]+)\s+to\s+/, '$1 ') .replace(/\s+to\s+([^0-9]+$)/, ' $1'); // 输出:'By Appointment : 10 am to 8 pm'
- 第一个正则
/(^[^0-9]+)\s+to\s+/:匹配开头非数字(非时间)的片段,把后面跟着的to换成空格。 - 第二个正则
/\s+to\s+([^0-9]+$)/:匹配末尾非数字的片段,把前面跟着的to换成空格。
方案二:通用正则替换函数(适配更多场景)
如果以后可能出现非时间内容在中间的情况,用替换函数判断to的前后是否都是时间格式,只保留时间之间的to:
function formatMatches(matches) { return matches.join(' to ').replace(/\s+to\s+/g, (match, offset, str) => { // 检查匹配位置的前后是否都是时间格式(数字+am/pm) const isPrevTime = /\d+\s*(am|pm)$/i.test(str.slice(0, offset)); const isNextTime = /^\d+\s*(am|pm)/i.test(str.slice(offset + match.length)); // 只有前后都是时间时保留to,否则换成空格 return isPrevTime && isNextTime ? ' to ' : ' '; }); } // 测试第一种情况 console.log(formatMatches(['10 am', '5 pm', 'by appointment only'])); // 输出:'10 am to 5 pm by appointment only' // 测试第二种情况 console.log(formatMatches(['By Appointment :', '10 am', '8 pm'])); // 输出:'By Appointment : 10 am to 8 pm'
内容的提问来源于stack exchange,提问作者rubyist
相关产品推荐
相关产品推荐

