Regex 左括号三位数右括号的正则表达式,即[123]或[368],替换为'';

Regex 左括号三位数右括号的正则表达式,即[123]或[368],替换为'';,regex,perl,replace,sed,Regex,Perl,Replace,Sed,我正在寻找一个正则表达式,它将匹配5个字符串,如标题中显示的两个字符串。下面是一个示例输入字符串 This is a sentence that doesn't contain any matches of the regex. This is a sentence that has two matches of the string at the end of the sentence [411] [101]. This is a sentence that has three mat

我正在寻找一个正则表达式,它将匹配5个字符串,如标题中显示的两个字符串。下面是一个示例输入字符串

This is a sentence that doesn't contain any matches of the regex.  
This is a sentence that has two matches of the string at the end of the sentence [411] [101].  
This is a sentence that has three matches [876] [232] [323].
我希望看到一个用perl或sed从文本文件中删除这些字符串的解决方案,以及一个从短字符串中删除这些字符串的解决方案。我不熟悉正则表达式、perl和sed。我尝试使用一个反向正则表达式工具,它似乎给了我这个正则表达式,但我找不到一种方法将它与perl或sed一起使用

\\[\\d\\d\\d\\]
然后我用perl做了类似的尝试,但没有取得任何进展

perl -p -i -e 's/\\[\\d\\d\\d\\]/""/g' textFileToRemoveRegexMatches.txt
这个怎么样:

>>> 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,它是<强> s >强> TRAAM <强> ED < /强>。除了作为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'

尝试下一种方法:

my $str = 'word [123] word [456]';
my $regex = qr/\[\d{3}\]/p;
my $subst = '';

my $result = $str =~ s/$regex/$subst/rg;
但也许您想使用该命令。e、 g

Perl中的解决方案:

$ echo 'one[876] two[232] three[323]' | perl -pe 's/\[\d{3}\]//g;'
印刷品:

one two three
one two three
Sed中的解决方案:

$ echo 'one[876] two[232] three[323]' | sed 's/\[[[:digit:]]\{3\}\]//g;'
印刷品:

one two three
one two three
这些示例使用了实时命令行界面,但您也可以将代码放入脚本文件中以供重用,如下所示:

Perl脚本:

#! /usr/bin/perl -p
# purge-bracket-numbers.perl
s/\[\d{3}\]//g
Sed脚本:

#! /usr/bin/sed -f
# purge-bracket-numbers.sed
s/\[[[:digit:]]\{3\}\]//g