从字符串中删除括号内的任意字符序列

Removing an arbitrary sequence of characters inside brackets from a string

我想从方括号内的字符串中删除一些字符,而不管字符的类型以及方括号内的字符数量。但是,括号的类型及其顺序不会改变。最后,我也想删除方括号。

例如:

my_string1 = 'this[123]'
my_string2 = 'is[7]'
my_string3 = 'my[i]'
my_string4 = 'example[jk]'

期望的输出:

my_string1 = 'this'
my_string2 = 'is'
my_string3 = 'my'
my_string4 = 'example'

使用 re.sub() 对我不起作用:

import re
my_string1 = 'this[112]'
print(re.sub("[[]|[]]", "", my_string1))

我得到的最佳输出:

'this112'

使用模式 \[.+?\],它匹配文字 [,后跟一个或多个字符,然后是文字 ]。我们使用 non-greedy ? 以防括号中包含多个序列:

import re
my_string1 = 'this[123]'
my_string2 = 'is[7]'
my_string3 = 'my[i]'
my_string4 = 'example[jk]'

for s in [my_string1, my_string2, my_string3, my_string4]:
    print(re.sub(r'\[.+?\]', '', s))

这输出:

this
is
my
example

假设 [] 没有嵌套,那么使用下面的正则表达式 ...

\[[^\]]*\]

... 并用空字符串替换匹配项:

  1. \[ - 匹配 '['
  2. [^\]]* - 匹配 0 个或多个不是 ']' 的字符。
  3. \] - 匹配']'。

代码:

import re

tests = [
    'this[123]',
    'is[7]',
    'my[i]',
    'example[jk]',
]

for test in tests:
    test = re.sub(r'\[[^\]]*\]', '', test)
    print(test)

打印:

this
is
my
example