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

发布于 2025-01-18 03:56:44 字数 504 浏览 1 评论 0原文

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

例如:

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'

I want to remove some characters from a string which are inside square brackets, regardless of the type of character as well as the amount of characters inside the square brackets. However, the type of brackets and their order does not change. Lastly, I want to remove the square brackets as well.

For example:

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

Desired output:

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

Using re.sub() does not work for me:

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

The best output I got:

'this112'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

压抑⊿情绪 2025-01-25 03:56:45

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

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

Use the pattern \[.+?\], which matches a literal [, followed by one or more characters, followed by a literal ]. We use the non-greedy ? in case there are multiple sequences enclosed in brackets:

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 outputs:

this
is
my
example
一杯敬自由 2025-01-25 03:56:45

假设 [] 不是嵌套的,则使用以下正则表达式……

\[[^\]]*\]

并将匹配项替换为空字符串:

  1. \[ - 匹配 '['
  2. < code>[^\]]* - 匹配 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

Assuming that the [] are not nested, then use the following regex ...

\[[^\]]*\]

... and replace matches with the empty string:

  1. \[ - Matches '['
  2. [^\]]* - Matches 0 or more characters that are not ']'.
  3. \] - Matches ']'.

The code:

import re

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

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

Prints:

this
is
my
example
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文