我正在解析一个巨大的法规文件,我有一个特定的正则表达式用于非标准法规,因为它们与通常的模式不匹配。这是我使用的正则表达式:
\n(\d*[A-Z]?-\d*[A-Z]?-\d*[\.\d]*[A-Z]?[-\d*[\.\d]*[A-Z]?]?)(?= (?:Superseded|Repealed|Transferred|Obsolete|Reserved|Rejected|Omitted|Not|Executed)\.\s*\n)(?:\s|\stt.*|\.)(?:Superseded|Repealed|Transferred|Obsolete|Reserved|Rejected|Omitted|Not|Executed).\s*\n(.*?)\n\d*[A-Z]?-\d*[A-Z]?-\d*[\.\d]*[A-Z]?[-\d*[\.\d]*[A-Z]?]?
除了一些有问题的情况外,这个方法非常有效。你知道吗
当两个特殊情况紧接着出现时,它不起作用;例如:
34A-1-28废除。 34A-1-28号。由SL 1986,ch 295,§7废除。你知道吗
34A-1-28废除。 34A-1-28号。由SL 1986,ch 295,§7废除。
34A-6-88, Transferred.
(法规后面的逗号)34A-6-88 to 23-34-1A Repealed.
任何帮助解决这三个问题都将不胜感激。为了方便起见,我已经建立了一个regex101,其中包含了一大块我想要标记here的法规。你知道吗
如果你需要一个复杂的正则表达式,一步一步地构建它是很重要的。那是避免迷路的唯一方法。你知道吗
开始前注意两个问题:
我不熟悉法律术语。我的术语可能全错了。
我将使用verbose flag。有了这个标志,您可以在正则表达式中自由地插入空格,以提高可读性。
让我们从法规号开始,定义一个解析单个组件的正则表达式(例如
34A
或83.1
)。你知道吗其中三到五个组成部分,用破折号隔开,构成一个完整的法规编号。你知道吗
有了这个,我们就可以定义一个既匹配一个规约又匹配一个范围的正则表达式。我们用两个小组来收集法规。第二个将是空的,因为没有给出范围。你知道吗
现在我们可以构造一个模式来匹配整个第一行。在这一点上,很容易处理有时出现的逗号。你知道吗
我不太清楚你要匹配多少文本。我的印象是,你想捕捉到下一个法令的开头,这是一个以法令编号开始的行。所以:
将这些组合起来,就可以得到正则表达式:
See it in action.
示例文本:
我假设你想把这段文字分成块,用引用的法规隔开。你知道吗
如果是这样,简化regex。你可以做:
注:
^
与re.S | re.M
组合使用(?=\n\n|\n+\Z|\Z)
的正向展望移到末尾。你知道吗Example in regex101
一旦有了单独的块,就可以进一步解析这些块以找到所需的内容。举个简单的例子:
它将示例文本分为各种法规的状态(颁布、废除、修改等)
像这样:
举一个regex有多简单的例子,至少在示例文本中,您可以使用Python的
split
方法和\n\n
返回来获得相同的结果:相关问题 更多 >
编程相关推荐