You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python正则表达式提取标签及标签间对应文本?

正则提取大写标签及后续内容的解决方案

问题场景

要从这段文本里提取所有大写标签(比如DEFINITION、CATEGORY),以及每个标签到下一个标签之间的内容:

Iron DEFINITION it is a chemical element with symbol Fe (from Latin: ferrum) and atomic number 26. CATEGORY It is a metal that belongs to the first transition series and group 8 of the periodic table. APPEARANCE A shiny, greyish metal that rusts in damp air, Its USE AND PROPERTIES Most is used to manufacture steel, used in civil engineering (reinforced concrete, girders etc) and in manufacturing. HISTORY Iron objects have been found in Egypt dating from around 3500 BC. They contain about 7.5% nickel, which indicates that they were of meteoric origin. MISC. It is, by mass, the most common element on Earth, right in front of oxygen (32.1% and 30.1%, respectively), forming much of Earth's outer and inner core. It is the fourth most common element in the Earth's crust.

预期输出是这样的:
Label: DEFINITION
Text: it is a chemical element with symbol Fe (from Latin: ferrum) and atomic number 26.
Label: CATEGORY
Text: It is a metal that belongs to the first transition series and group 8 of the periodic table.
(以此类推覆盖所有标签)

你写的原正则没法正常工作:

(DEFINITION|CATEGORY|USE AND PROPERTIES|MISC.|HISTORY)(.*)((?=DEFINITION)|(?=CATEGORY)|(?=USE AND PROPERTIES)|(?=MISC.)|(?=HISTORY))

修正后的正则方案

可用的正则表达式

(\b(?:DEFINITION|CATEGORY|APPEARANCE|USE AND PROPERTIES|MISC\.|HISTORY)\b)\s*(.*?)(?=\s*\b(?:DEFINITION|CATEGORY|APPEARANCE|USE AND PROPERTIES|MISC\.|HISTORY)\b|$)

关键调整点

  • 加单词边界\b:避免标签被部分匹配,比如防止类似DEFINITIONS这种带后缀的词被误识别,保证只匹配完整的标签单词。
  • 换成非贪婪匹配.*?:原正则用的.*是贪婪模式,会直接匹配到最后一个标签前的所有内容,改成.*?后,会精准停在第一个出现的下一个标签前,刚好对应一段内容。
  • 补充文本结尾条件|$:最后一个标签后面没有下一个标签,得让正则知道匹配到文本结束为止,不然最后一段内容会提取不到。
  • 补上漏掉的APPEARANCE标签:样本文本里有这个标签,原正则没包含,自然提取不到这部分内容。
  • 转义MISC.里的点号:正则中.代表匹配任意字符,必须写成MISC\.才能准确匹配带点的标签。

匹配逻辑

  • 第一个捕获组:提取完整的标签文本
  • 第二个捕获组:提取当前标签到下一个标签(或文本结尾)之间的内容
  • 用\s*处理标签前后的空白,避免内容里带多余空格

内容的提问来源于stack exchange,提问作者mgilsn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:01:00