如何为多次出现的分隔字符串编写正则表达式

2024-09-26 18:02:38 发布

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

我可以得到多个以$startMsg$开始,以$endMsg$结束的字符串。因此,以下是可接受和不可接受的:

  1. $startMsg$abcd$endMsg$:允许
  2. $startMsg$abcd$endMsg$aaa:不允许,因为$endMsg$后面有aaa
  3. 应为$startMsg$,但只找到$endMsg$。
    $startMsg$abcd$endMsg$xyz$endMsg$:不允许
  4. 找不到匹配的$endMsg$。
    $startMsg$abcd$endMsg$xyz$startMsg$:不允许
  5. $startMsg$abcd$endMsg$xyz$startMsg$dad$endMsg$:允许
  6. 在$startMsg$之前找到$endMsg$。
    $startMsg$abcd$endMsg$xyz$endMsg$dad$startMsg$:不允许
  7. aaa$startMsg$abcd$endMsg$:不允许,因为在$startMsg$之前有aaa

我试过这样的方法:

 ^((\$startMsg\$[^(\$startMsg\$>>)(\$endMsg\$)]*\$endMsg\$))*$

我可以得到多个以$startMsg$开始,以$endMsg$结束的字符串。因此,以下是可接受和不可接受的:

  1. $startMsg$abcd$endMsg$:允许
  2. $startMsg$abcd$endMsg$aaa:不允许,因为$endMsg$后面有aaa
  3. 应为$startMsg$,但只找到$endMsg$。
    $startMsg$abcd$endMsg$xyz$endMsg$:不允许
  4. 找不到匹配的$endMsg$。
    $startMsg$abcd$endMsg$xyz$startMsg$:不允许
  5. $startMsg$abcd$endMsg$xyz$startMsg$dad$endMsg$:允许
  6. 在$startMsg$之前找到$endMsg$。
    $startMsg$abcd$endMsg$xyz$endMsg$dad$startMsg$:不允许
  7. aaa$startMsg$abcd$endMsg$:不允许,因为在$startMsg$之前有aaa

我试过这样的方法:

 ^((\$startMsg\$[^(\$startMsg\$>>)(\$endMsg\$)]*\$endMsg\$))*$
  • ^at start:字符串的开头
  • \$:转义$
  • $结尾:字符串的结尾

但这似乎大错特错。你知道吗

但这似乎大错特错。在python中我是如何做到这一点的?你知道吗

允许[^(\$startMsg\$>>)(\$endMsg\$)]*匹配任何不包含$startMsg$$endMsg$的字符串。似乎是这样,不是吗?但是如果不完成regex,我该怎么做呢?你知道吗

或者,这在regex中是可撤销的,因为它与下推自动机相关,因此在finiteautomatic/regex中是绝对可撤销的。你知道吗


Tags: 方法字符串自动机结尾startatregexabcd
2条回答

检查这个正则表达式,它对您提到的示例很好。你知道吗

^(\$startMsg\$)((\w)*(\$endMsg\$\w+\$startMsg\$)*(\w)*)*(\$endMsg\$)$

如果在开始和结束之间除了字符之外还有其他内容,请更改\w。你知道吗

如果你只是想抓住字符串开头和结尾之间的字符,那么在上面应用下面的正则表达式

(?<=\$startMsg\$)\w+(?=\$endMsg\$)

这张单子会给你人物。你知道吗

If you really want to use regex

^((\$startMsg\$)[^$]*?(\$endMsg\$)(([^$]*?)(?=\$startMsg\$)|.{0}))*?$

不幸的是,不能对字符序列使用[]构造,只能对单个字符使用。因此,您可以使用LookAhead/lookback((?=...)(?<=...)和一个惰性量词来匹配所有内容,直到那个序列,就像我对([^$]*?)(?=\$startMsg\$)所做的那样。你知道吗

不过,我要提一提的是,绝对有其他方法比这一团热更具可读性。Regex很酷,但像这样的复杂序列令人困惑,难以理解,应该尽可能避免。你知道吗

相关问题 更多 >

    热门问题