如何用正则提取每个TITLE到下一个TITLE前的含DESCRIPTION的全部内容
解决方案
方案1:正则匹配
直接使用以下正则即可匹配符合要求的内容:/TITLE:[\s\S]*?(?=\s*TITLE:|$)/g
实现代码
// 你的原始数据 const data = `TITLE: Hitchhiker's Guide to the Galaxy AUTHOR: Douglas Adams DESCRIPTION: Seconds before the Earth is demolished to make way for a galactic freeway, Arthur Dent is plucked off the planet by his friend Ford Prefect, a researcher for the revised edition of The Hitchhiker's Guide to the Galaxy who, for the last fifteen years, has been posing as an out-of-work actor. TITLE: Dune AUTHOR: Frank Herbert DESCRIPTION: The troubles begin when stewardship of Arrakis is transferred by the Emperor from the Harkonnen Noble House to House Atreides. The Harkonnens don't want to give up their privilege, though, and through sabotage and treachery they cast young Duke Paul Atreides out into the planet's harsh environment to die. There he falls in with the Fremen, a tribe of desert dwellers who become the basis of the army with which he will reclaim what's rightfully his. Paul Atreides, though, is far more than just a usurped duke. He might be the end product of a very long-term genetic experiment designed to breed a super human; he might be a messiah. His struggle is at the center of a nexus of powerful people and events, and the repercussions will be felt throughout the Imperium. TITLE: A Song Of Ice And Fire Series AUTHOR: George R.R. Martin DESCRIPTION: As the Seven Kingdoms face a generation-long winter, the noble Stark family confronts the poisonous plots of the rival Lannisters, the emergence of the White Walkers, the arrival of barbarian hordes, and other threats.` const result = data.match(/TITLE:[\s\S]*?(?=\s*TITLE:|$)/g) || [] // 可选:去除每一项末尾多余的空白字符 const trimmedResult = result.map(item => item.trimEnd()) console.log(trimmedResult)
正则说明
TITLE:固定匹配每一条内容的开头标记[\s\S]*?非贪婪匹配所有字符(包括换行符,规避JS里.默认不匹配换行的问题)(?=\s*TITLE:|$)正向预查,匹配到下一个TITLE:前的位置或者字符串末尾,不会把下一个TITLE:计入匹配结果
方案2:split拆分(更简单高效)
如果你的文本结构固定都是以TITLE:开头分隔,不需要正则也能实现,性能更好:
const result = data.split('TITLE:') .filter(Boolean) // 过滤掉拆分后的空字符串 .map(item => `TITLE: ${item.trim()}`) // 补回开头的TITLE标识并去除多余空白
两种方案输出的结果都和你要求的预期完全一致。
内容的提问来源于stack exchange,提问作者visylvius
相关产品推荐
相关产品推荐

