如何使用JavaScript正则表达式正确拆分带有序号标记的文本
JavaScript 正则拆分带(数字)序号文本方案
原有正则问题说明
你当前使用的正则存在两处核心错误:
- 量词
{1,3}位置错误,写在了右括号外侧,没有对数字位数做限制,匹配逻辑不符合预期 - 结尾固定匹配
(作为终止符,既会漏掉最后一段没有后续(的内容,也可能因为文本中间出现括号导致匹配截断错误
正确正则模式
使用带正向预查的正则即可完成需求:
/\((\d{1,3})\)\s*(.+?)\s*(?=\(\d{1,3}\)|<\/|$)/g
各部分逻辑说明:
\((\d{1,3})\):匹配带括号的序号,同时捕获1-3位的数字作为序号id\s*:过滤序号和正文之间的多余空白字符(.+?):非贪婪匹配序号对应的正文内容(?=\(\d{1,3}\)|<\/|$):正向预查设置终止条件,遇到下一个序号、遇到HTML闭合标签、或者到文本末尾时停止匹配,不会消耗终止字符,不影响后续序号的识别
完整实现代码
const rawText = `<p><em>(1) Really not. (2) Uh huh. (3) Behold Prince (4) are key in his natural element, cowering at the mercy of the women in his life. (5) See me perhaps you'd like to spout with my daughters and teach them some combination. (6) No doubt you are the best teacher, your majesty. (7) It is my daughter's that teach me in the languages of the modern world, for instance.</em></p>` const reg = /\((\d{1,3})\)\s*(.+?)\s*(?=\(\d{1,3}\)|<\/|$)/g // 输出二维数组格式 const array2d = [] // 输出对象数组格式 const objArray = [] let matchResult while ((matchResult = reg.exec(rawText)) !== null) { const id = Number(matchResult[1]) const text = matchResult[2] array2d.push([id, text]) objArray.push({id, text}) }
执行后输出的前三项和你给出的示例完全一致,可完整匹配所有7条内容。
内容的提问来源于stack exchange,提问作者Todor Iliev
相关产品推荐
相关产品推荐

