查找字符串中所有在两侧都只有一个括号的子字符串 [英] Find all the substrings in a string that only have a single bracket on both sides

查看:120
本文介绍了查找字符串中所有在两侧都只有一个括号的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找字符串的所有子字符串,该字符串的两边都只有一个括号.

I'm trying to find all the substrings in a string that only have a single bracket on both sides.

示例:'(pop((hello world))(goodbye(now))(hi)jump)'

我想获得以下列表:['(hi)', '(pop((hello world))(goodbye(now))(hi)jump)'] 因为它们是唯一在两边都带有一个括号的子字符串.

(由于'(now))(hi)jump)'之类的子字符串不完整,因此不算在内).

I would like to get this list: ['(hi)', '(pop((hello world))(goodbye(now))(hi)jump)'] because they are the only substrings that have exactly one bracket on both sides.

(substrings like '(now))(hi)jump)' don't count because they aren't complete).

我的代码在这里:

import re
l = '(M264/M274)+(((551/882)+362/(362/551/882)+889)/((551/882)+362/(362/551/882)+889)+(241/242/275/550/551+882/889/362))'
print(re.findall(r"[^\(.](\([^\(.].*?[^\).]\))[^\).]", l))

将返回:

['(362/551/882)', '(362/551/882)']

我不确定如何使其包含(M264/M274). 请帮助我.

I'm not sure how to make it include (M264/M274). Please assist me.

推荐答案

使用像[^\(.][^\).]这样的否定字符类,可以匹配未在字符类中列出的任何字符,并且至少需要一个字符.这部分 .*?可以匹配换行符以外的任何字符,因此也可以匹配括号.

Using a negated character class like [^\(.] and [^\).] match any char that is not listed in the character class and require at least a single char. This part .*? can match any char except a newline, so it can also match parenthesis.

它没有考虑到括号之间的平衡,但是,如果您要像问题中那样匹配(M264/M274),则可以结合使用环视功能和

It does not take balanced parenthesis into account, but if you want to match (M264/M274) like in your question, you could use lookarounds in combination with a negated character class

(?<!\()\([^()]+\)(?!\))

部分

  • (?<!\()负向后看,断言左侧不是(
  • \(匹配(
  • [^()]+匹配除()
  • 以外的任何字符
  • \)匹配)
  • (?!\))前瞻为负,断言右侧的内容不是`)
  • (?<!\() Negative lookbehind, assert what is on the left is not (
  • \( Match (
  • [^()]+ Match any char except ( or )
  • \) Match )
  • (?!\)) Negative lookahead, assert what is on the right is not `)

正则表达式演示

如果要匹配2个左括号和右括号,还可以使用环顾四周,请注意,这也没有考虑均衡的括号.

If you want to match 2 opening and closing parenthesis, you can also make use of lookarounds and note that this also does not take balanced parenthesis into account.

(?<!\()\(\((?!\().*?\)\)(?<!\)..)(?!\))

部分(使用相同的机制或环顾四周,仅这次使用.*?

  • (?<!\()负向后看,断言左侧不是(
  • \(\(匹配((
  • (?!\))前瞻为负,断言右侧的内容不是`)
  • .*?匹配除换行符0次以上以外的所有字符
  • \)\)匹配))
  • (?<!\)..)后面是负数,请断言))之前的)
  • (?!\))前瞻为负,断言右侧的内容不是`)
  • (?<!\() Negative lookbehind, assert what is on the left is not (
  • \(\( Match ((
  • (?!\)) Negative lookahead, assert what is on the right is not `)
  • .*? Match any char except a newline 0+ times
  • \)\) Match ))
  • (?<!\)..) Negative lookbehind, assert not a ) before ))
  • (?!\)) Negative lookahead, assert what is on the right is not `)

正则表达式演示

这篇关于查找字符串中所有在两侧都只有一个括号的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆