gpt4 book ai didi

python - 正则表达式中的可选括号

转载 作者:行者123 更新时间:2023-12-01 03:55:23 24 4
gpt4 key购买 nike

在 python 中使用以下字符串

1 - GENERAL 1

1.1 RELATED DOCUMENTS 1

1.2 SUMMARY 1

1.3 DEFINITIONS 1

1.4 INFORMATIONAL SUBMITTALS 2

1.5 GENERAL COORDINATION PROCEDURES 2

1.6 COORDINATION DRAWINGS 3

1.7 REQUESTS FOR INFORMATION (RFIs) 4

1.8 PROJECT MEETINGS 6

我正在尝试创建一个 regit 表达式,将部分、标题和页码分为 3 组。到目前为止我已经

 (\d)(\.|\d|\s|-)+\s+([^a-z]+?)\s+\d

它可以处理除(RFI)之外的所有情况。我也能捕获这个吗?注意:有时字符串可能包含我不想要的小写小节。这就是 [^a-z] 出现的原因。此外,RFI 可能并不总是括号中的文本。

更新:

END OF SECTION



Project No. 151219.00 012500 - 1 of 3 Substitution Procedures

Rev. 0, 07/23/15

Issued for Construction

最佳答案

字符串中主要包含三个部分。

First is section which is mainly composed of digits followed by decimal and digits

Second is anything upto page number. This mainly starts from word

Third is page number in the last which is usually digits

您的正则表达式包含太多不需要的替换。所以你可以使用这个正则表达式

^\s*(\b\d+(?:[.]\d+)?)\W+(.*?)\s*(\b\d+\b)$
<----------------> <---> <------->
Section Content Page Number

<强> Regex Demo

如果小节可以包含 1.1.1 等值,您可以使用

^\s*(\b\d+(?:[.]\d+)*)\W+(.*?)\s*(\b\d+\b)$

正则表达式分解

\b is word boundary

\W is equivalent to [^\w] which in turn is [^A-Za-z0-9_] (Mind the ^ which signifies match anything except those in character class)

 ^ #start of string
\s* #Match any spaces in starting
(
\b #word boundary
\d+ #Match digits
(?:[.]\d+)* #Non-capturing group to match . followed by digits any
#number of times(due to *). It matches after . like .1.1 etc
)
\W+ #Match any non word character
(.*?) #Match anything upto page number given in next
\s* #Match spaces if there
(\b\d+\b) #Match page numbers in last(due to $).
$ #End of string

关于python - 正则表达式中的可选括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37553317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com