这个怎么样:
>>> s = "Hello world [123] this is some text"
>>> e = r'\[\d{3}\]'
>>> import re
>>> re.sub(e, '', s)
'Hello world this is some text'
如果您想大规模执行此操作,请考虑使用 sed,它是 stream editor。除了作为 macOS 上的核心实用程序之外,它还适用于所有 Linux 风格。
我用这两行创建了一个示例文件:
This is line one with [123] and needs to be substituted.
This is a longer line, lets call it line 2 that has [this thing] that should not be replaced, but [345] that should.
您使用 sed 的方式是传递一个替换表达式。命令s 表示替换,g 表示替换所有匹配项,而不仅仅是第一个匹配项。
接下来,您将要搜索的表达式和中间替换为字符。常见的规范是使用/,但您可以使用任意两个在您的shell 中没有特殊含义的相似字符。
所以,sed 命令是:
sed s/search-for-this/replace-with-this/g the-name-of-the-file.txt
如果您键入以上内容,sed 将简单地返回它所替代的内容。这是我们的正则表达式的示例:
$ sed 's/\[[0-9]\{3\}\]//g' test.txt
This is line one with and needs to be substituted.
This is a longer line, lets call it line 2 that has [this thing] that should not be replaced, but that should.
sed 的默认行为是返回结果;并且它不会修改原始文件(因为它旨在处理流)。
要让 sed 更改原始文件,请传递 -i 参数,这意味着 就地 - 也就是说,在文件本身中进行替换,如下所示:
$ sed -i 's/\[[0-9]\{3\}\]//g' test.txt
请注意,这一次,它没有返回任何内容,但是,如果我们检查它已被修改的文件:
$ cat test.txt
This is line one with and needs to be substituted.
This is a longer line, lets call it line 2 that has [this thing] that should not be replaced, but that should.
注意:如果你使用的是 mac,你可能需要使用sed -i '.bak'