正则表达式向前匹配贪婪的反向词

问题描述 投票:0回答:2

我试图只匹配里面有“TEST”的段落索引,但我的正则表达式也匹配没有它的段落,因为下一个有“TEST”。

你能帮我详细说明一下,一般来说,如何只匹配第一次出现的模式,然后再匹配其他模式吗?

asdasdasda
2.1 adasdasdasdasdwvwetwevtwtv
wetvwetv TEST wqrqwvrqw
qwvrqwvqwr
2.2 whergtvwe
wetvwetvwetveatw
evtwet
2.3 eyrnenytunrunert
vqevrerwv TEST aevtawtvwetv

^(\d+.\d+)(?=.*?测试)

regex regex-lookarounds
2个回答
0
投票

这个正则表达式只匹配后面没有跟

\d\.\d
的字符:demo

^(\d+\.\d+)(?=(?:.(?!\d\.\d))*TEST)

如果您希望它只匹配句点而不是通配符,则必须转义数字之间的句点。


0
投票

感兴趣的“段落”可以通过匹配以下正则表达式得到。

^\d+\.\d+\s(?:(?!^\d+\.\d+\s)[\s\S])*\bTEST\b(?:(?!^\d+\.\d+\s)[\s\S])*

带有以下标志:

  • g
    :“全球”,第一场比赛后不要返回
  • m
    :“多行”,导致'^'和'$'分别匹配一行的开头(而不是匹配字符串的开头和结尾)

演示

表达式可以分解如下

^                # match beginning of a line
\d+\.\d+\s       # match 1+ digits then '.' then 1+ digits then a whitespace 
(?:              # begin a non-capture group
  (?!            # begin a negative lookahead
    ^            # match beginning of a line
    \d+\.\d+\s   # match 1+ digits then '.' then 1+ digits then a whitespace 
  )              # end the negative lookahead
  [\s\S]         # match any character, including line terminators
)                # end non-capture group
*                # execute the non-capture group 0+ times
\bTEST\b         # match 'TEST' with word breaks on both sides
(?:              # begin a non-capture group
  (?!            # begin a negative lookahead
    ^            # match beginning of a line
    \d+\.\d+\s   # match 1+ digits then '.' then 1+ digits then a whitespace 
  )              # end the negative lookahead
  [\s\S]         # match any character, including line terminators
)                # end non-capture group
*                # execute the non-capture group 0+ times
© www.soinside.com 2019 - 2024. All rights reserved.