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

标签 python regex

在 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/

相关文章:

Java replaceAll() 出现,除了一些词

python 加速这个正则表达式子

python - 在 pandas groupby 中提取一系列相同数字中的第一个数字

python - Jinja2:在循环内更改变量的值

python - 如何找到字典中哪个键具有最长的值列表?

在不一致的时间序列上使用 Pandas 的 Python EMA

sql - 如何使用 SQL 替换电话号码中的某些字符?

python - 正则表达式 - 匹配一个单词,但不匹配可能出现在短语中任何位置的短语

Java:从 URL 获取整数值

python - 找到坡度最陡的点 python