python - 正则表达式只匹配各种括号外的内容

标签 python regex perl

对于这个字符串:hello(你好,[is] socool)真棒{yeah} 我希望正则表达式只匹配 helloawesome

这是我迄今为止尝试过的,它似乎不起作用。 https://regex101.com/r/NsUfQR/1

([^\(\)\[\]\{\}[]()〔〕〈〉【】]+)(?![^()\[\]\{\}[ ]()〔〕〈〉【】]*[\)\])]〉】]])

这匹配 hello hi that awesome yeah 太多了。

是否可以仅使用正则表达式来实现这一点,或者使用 perl 或 python 是否有另一种方法?

最佳答案

这个正则表达式只使用普通的文本括号 (),[],{}
您可以添加自己的,只需复制一个 block ,粘贴它并更改分隔符
你想要的括号。注意递归组。
在排除列表中添加前括号。
另请注意,最后有一个跌落通过 [\S\s] 来拾取任何流浪者。

更新添加了所有括号类型(来自评论)。

/(?:[^\(\[{〈【〔〔】+|(?:(\((?>[^())]++|(?1))*\) )|({(?>[^{}]++|(?2))*})|(\[(?>[^\[\]]++|(?3))*\])| (〈(?>[^〈〉]++|(?4))*〉)|(【(?>[^【】]++|(?5))*】)|(〔(?>[ ^〔〕]++|(?6))*])|(((?>[^()]++|(?7))*))|([(?>[^[]]++ |(?8))*]))(*SKIP)(*FAIL)|[\S\s])/
https://regex101.com/r/LUXJVu/1

 (?:
    [^\(\[{〈【〔([]+ 
  | 
    (?:
       (                   # (1 start), Left/Right parenthesis
          \(    
          (?>
             [^()]++ 
           | (?1) 
          )*
          \)                     
       )                   # (1 end)
     | 
       (                   # (2 start), Left/Right curly bracket
          {
          (?>
             [^{}]++ 
           | (?2) 
          )*
          }
       )                   # (2 end)
     | 
       (                   # (3 start), Left/Right square bracket
          \[ 
          (?>
             [^\[\]]++ 
           | (?3) 
          )*
          \] 
       )                   # (3 end)
     | 
       (                   # (4 start), Left/Right angle bracket
          〈
          (?>
             [^〈〉]++ 
           | (?4) 
          )*
          〉
       )                   # (4 end)
     | 
       (                   # (5 start), Left/Right black lenticular bracket
          【
          (?>
             [^【】]++ 
           | (?5) 
          )*
          】
       )                   # (5 end)
     | 
       (                   # (6 start), Left/Right tortoise bracket
          〔
          (?>
             [^〔〕]++ 
           | (?6) 
          )*
          〕
       )                   # (6 end)
     | 
       (                   # (7 start), Left/Right fullwidth parenthesis
          (
          (?>
             [^()]++ 
           | (?7) 
          )*
          )
       )                   # (7 end)
     | 
       (                   # (8 start), Left/Right fullwidth square bracket
          [
          (?>
             [^[]]++ 
           | (?8) 
          )*
          ]
       )                   # (8 end)
    )
    (*SKIP) (*FAIL) 
  | 
    [\S\s] 
 )

关于python - 正则表达式只匹配各种括号外的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64254055/

相关文章:

python - 如何使用正则表达式匹配文本行中任意位置的价格编号?

perl - 我应该如何使用 Perl 模块分发数据文件?

perl - 安装 Perl mod 后,不断收到错误 "Can' t locate Image/Grab.pm in @INC”

regex - 如何在 Perl 中只保留变量中的数字?

java - 如何读取文件中某个字符后的内容

python - 在用户定义的函数中访问全局框架

python - 声明性 SQLAlchemy 中的标签字典?

python - 有没有办法使用 TRAINS python 包创建一个比较超参数与模型精度的图表?

python - 为什么 urllib 不适用于本地网站?

python - Pandas Python-read_csv 未读取每一行的完整数据