使用Pandas捕获regex负lookback

2024-05-06 01:34:16 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于这些条件:

START-h1-/h1-p-code-/code-code-/code-code-/code-/p-h1-/h1-ol-li-code-/code-p-code-/code-/p-/li-li-code-/code-/li-p-code-/code-/p-li-code-/code-/li-p-code-/code-/p-li-code-/code-code-/code-p-code-br-postmaster@domainname.com-br-br-br-br-br-br-br-br-br-br-br-br-br-br-br-/postmaster@domainname.com-/code-/p-/li-br-li-/li-li-p-code-/code-/p-/li-/ol-p-b-/b-/p-ul-li-/li-li-code-/code-/li-li-code-/code-/li-li-a-/a-/li-/ul-p-a-/a-/p

START-p-code-/code-/p-p-/p-h2-/h2-p-/p-p-code-/code-/p-p-code-/code-code-/code-code-/code-code-/code-code-/code-code-/code-code-/code-/p-p-code-/code-/p-ul-li-strong-/strong-code-/code-/li-li-strong-/strong-code-/code-/li-li-strong-/strong-code-/code-code-/code-/li-li-strong-/strong-code-/code-/li-li-strong-/strong-code-/code-/li-li-strong-/strong-code-/code-/li-li-strong-/strong-code-/code-/li-li-strong-/strong-code-/code-code-/code-/li-li-strong-/strong-code-/code-/li-li-strong-/strong-code-/code-/li-/ul-p-code-/code-/p-h3-/h3-p-code-/code-/p-p-code-/code-code-/code-br-br-code-br-br-/code-code-br-br-br-br-br-br-br-br-/code-/p-h3-/h3-p-/p-p-code-/code-/p-ol-/ol

START-h1-/h1-p-a-/a-/p-p-a-/a-/p-p-strong-/strong-br-/p-p-strong-/strong-br-/p-h1-/h1-ul-li-code-/code-/li-li-ul-br-li-/li-li-code-/code-/li-/ul-/li-/ul-h1-strong-/strong-/h1-ol-li-strong-/strong-/li-li-strong-/strong-strong-/strong-/li-li-strong-/strong-strong-/strong-strong-/strong-/li-/ol-h1-strong-/strong-/h1-ol-li-strong-/strong-ul-br-li-code-/code-/li-li-code-/code-/li-/ul-/li-br-li-strong-/strong-/li-li-code-/code-/li-/ol-h1-a-/a-/h1-p-br-/p

START-h1-/h1-p-/p-p-/p-ul-li-a-/a-/li-li-a-/a-/li-/ul-p-strong-/strong-br-/p-h1-/h1-ol-li-strong-/strong-strong-/strong-br-br-img-/li-br-li-strong-/strong-strong-/strong-br-br-img-/li-br-li-strong-/strong-br-br-img-/li-br-li-strong-/strong-strong-/strong-br-br-img-/li-br-li-strong-/strong-strong-/strong-strong-/strong-strong-/strong-strong-/strong-strong-/strong-br-br-img-/li-br-li-strong-/strong-strong-/strong-br-br-img-/li-br-br-li-strong-/strong-strong-/strong-br-br-img-/li-br-li-strong-/strong-strong-/strong-br-br-img-/li-/ol-p-strong-/strong-strong-/strong-/p-h1-a-/a-a-/a-/h1-p-br-/p-p-/p

这个正则表达式模式:

((?<!\/li|-[ou]l)-li|(?<!\/li|\/[ou]l)-\/[ou]l)

如何将-li左侧的部分捕捉回下一个-字符

正如您在这里的演示https://regex101.com/r/nrNVt9/1中所看到的,该模式当前仅捕获-li,但我需要捕获/提取,例如:-/p-li-ol-/ol-br-li,等等。无论-li左边的是什么,都将向左移动到下一个“-”,然后将其包括在内,然后停止

注意:我正在使用python/pandas和str.extract,因此必须平衡模式,否则会出现错误:

error: look-behind requires fixed-width pattern

我想负面的回顾让我困惑


Tags: brcomimg模式codeouliul
1条回答
网友
1楼 · 发布于 2024-05-06 01:34:16

您可以使用一个负的前向(?!和两个捕获组,并交替使用这两个备选方案,而不是使用后向查找

(?!-[ou]l|-/li)(-[^-\r\n]+)-li|(?!-/[ou]l|-/li)(-[^-\r\n]+)-/[ou]l

解释

  • (?!-[ou]l|-/li)断言右边的不是-ol-ul-/li
  • (-[^-\r\n]+)-li在组1中捕获匹配除--li之外的任何字符
  • |
  • (?!-/[ou]l|-/li)断言右边的不是-/ol-/ul-/li
  • (-[^-\r\n]+)-/[ou]l在组1中捕获匹配除-之外的任何字符的字符,并匹配-/ol-/ul

Regex demo

相关问题 更多 >