从字符串中删除括号内部字符的任意顺序
我想从平方括号内的字符串中删除一些字符,而不管方括号内的字符类型以及字符的数量如何。但是,支架的类型及其顺序不会改变。最后,我也想卸下方括号。
例如:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用模式
\[.+?\]
,它匹配文字[
,后跟一个或多个字符,后跟文字]
。我们使用非贪婪的?
以防括号中包含多个序列:此输出:
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:This outputs:
假设
[]
不是嵌套的,则使用以下正则表达式……并将匹配项替换为空字符串:
\[
- 匹配 '['\]
- 匹配“]”。代码:
打印:
Assuming that the
[]
are not nested, then use the following regex ...... and replace matches with the empty string:
\[
- Matches '['[^\]]*
- Matches 0 or more characters that are not ']'.\]
- Matches ']'.The code:
Prints: