Python regex删除[Number]的所有出现

2024-05-19 15:05:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找python中的regex语句,它将从字符串中删除所有出现的[1]或[17]或基本上[*]。发生情况如下,其中*等于某个数:

[*]
[ * ]
[ *]
[* ]

目前我有:

re.sub(r'\[*\]', '', origional_string)

引发invalid expression

输入字符串示例:

makeup of organisms.[10] In 1997, while working at the University of Tennessee, Pigliucci received the Theodosius Dobzhansky Prize,[11] 

预期产量:

makeup of organisms. In 1997, while working at the University of Tennessee, Pigliucci received the Theodosius Dobzhansky Prize,

Tags: ofthe字符串inatworkingreceivedwhile
3条回答
 >>> import re
 >>> re.sub(r'\[\s*\d+\s*\]', '', original_string)

我想这样应该行得通:

import re

origional_string = "makeup of organisms.[10] In 1997, while working at the University of Tennessee, Pigliucci received the Theodosius Dobzhansky Prize,[11]"

result = re.sub(r'\[ *[0-9]+ *\]', '', origional_string)

print(result)

[0-9]+匹配一个或多个数字,而 *匹配空格(如果有)。你知道吗

ideone demo

\d表示正则表达式中的数字。我还在这里的数字周围添加了选项\s。你知道吗

re.sub(r'\[\s*\d+\s*\]', '', origional_string)

相关问题 更多 >