gpt4 book ai didi

Python 正则表达式 : How to implement a regex expression that checks for matching set of brackets?

转载 作者:行者123 更新时间:2023-12-01 00:21:10 25 4
gpt4 key购买 nike

我需要实现一个 python 正则表达式来捕获两个语句:

  1. 任何字符序列,但任何“{”都必须与“}”匹配
  2. 除“{”、“}”、“;”之外的任何字符序列

情况 2 很简单:r'[^\{\};]+

对于情况 1,我不确定。不允许嵌套括号,但“hello world {it is} {me}”应该可以。我现在最接近的是 r'.*?\{.*?\}.*?,但它匹配“an {apple}”,但不匹配“an {apple} boy”。我该如何纠正这个问题?

这些应该没问题:

{a} {boy} lives here
{a} boy {lives} here
a {boy} lives here
a boy lives here

这些都不行:

{{a} boy lives here}
a boy {{lives}} here
a boy {lives} here {
a boy lives here }

最佳答案

如果您的括号没有嵌套且没有转义,那么您可以使用此正则表达式来验证您的输入:

^(?:[^{}]*{[^}]*})*[^{}]*$

RegEx Demo

此正则表达式也将匹配空字符串。如果您想避免,请使用 (?!$) 否定前瞻来禁止空匹配:

^(?!$)(?:[^{}]*{[^}]*})*[^{}]*$

正则表达式详细信息:

  • ^:开始
  • (?::启动非捕获组
    • [^{}]*:匹配 0 个或多个非 {}
    • 的任何字符
    • {[^}]*}:匹配 {...} 子字符串
  • )*:结束非捕获组。 * 让该组重复 0 次或多次。
  • [^{}]*:匹配 0 个或多个非 {}
  • 的任何字符
  • $:结束

关于Python 正则表达式 : How to implement a regex expression that checks for matching set of brackets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58961708/

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