Python 删除括号内内容的正则表达式是什么?
我想做这样的事情Python 删除括号内内容的正则表达式是什么?,python,regex,Python,Regex,我想做这样的事情 Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5 到 什么是regex命令来实现这一点?您可以使用: 您希望跳出括号,并将非贪婪修饰符?与catch-all表达式+一起使用 >>> s = 'Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5' >>> re.s
Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5
到
什么是regex命令来实现这一点?您可以使用:
您希望跳出括号,并将非贪婪修饰符
?
与catch-all表达式+
一起使用
>>> s = 'Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5'
>>> re.sub(r'\[.+?\]\s*', '', s)
'Alice in the Wonderland Rating 4.5/5'
说明:
表示任何字符和
一次或多次出现。此表达式是“贪婪”表达式,将匹配所有内容(字符串的其余部分,包括任何右括号),因此需要使用非贪婪修饰符+
,使其在右括号处停止。请注意,?
表示零次或一次出现“x”,因此上下文很重要x?
- 如果要捕获“[]”,
表示零次或多次出现,请将其更改为*
*
表示任何空格字符\s
+?
。[^x]
表示不是“x”
,但结果表达式更难读取:\[[^\]+\]
Justhalf的观察非常有针对性:只要括号没有嵌套,这一条就有效。正则表达式不适合匹配任意数量的开括号和闭括号,但如果它们没有嵌套,可以使用此正则表达式完成:
import re
string = 'Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5'
re.sub('\[[^\]]+\]\s*','',string)
请注意,它还将删除括号后的所有空格。如果您更喜欢正则表达式中的大量
[]
:)
重申@justhalf所说的话。Python正则表达式不适合嵌套的
[
我认为最好在这两个地方都使用*
而不是+
。否则你就无法匹配[]
或[foo]bar
现在我记得为什么我停止编写Perl而支持Python:-)
>>> s = 'Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5'
>>> re.sub(r'\[.+?\]\s*', '', s)
'Alice in the Wonderland Rating 4.5/5'
import re
string = 'Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5'
re.sub('\[[^\]]+\]\s*','',string)
>>> import re
>>> s = 'Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5'
>>> re.sub('[[].*?[]]\s*', '', s)
'Alice in the Wonderland Rating 4.5/5'
>>> re.sub('[[][^]]*.\s*', '', s)
'Alice in the Wonderland Rating 4.5/5'