perl - 正则表达式之间的范围
perl - range between with regex
我有一个像
这样的文件
$ cat num_range.txt
rate1, rate2, rate3, rate4, rate5
pay1, pay2, rate1, rate2, rate3, rate4
rev1, rev2
rate2, rate3, rate4
我需要通过匹配前缀和数字范围来过滤逗号分隔的行。
例如 - 如果输入是“rate”并且范围是 2 到 5,那么我应该得到
rate2, rate3, rate4, rate5
rate2, rate3, rate4
rate2, rate3, rate4
如果是5比10,那我应该得到
rate5
当我使用 perl -ne ' while ( /rate(\d)/g ) { print "$&," } ; print "\n" ' num_range.txt
时,我得到了前缀的所有匹配项,
但是下面一个不行。
perl -ne ' while ( /rate(\d){2,5}/g ) { print "$&," } ; print "\n" ' num_range.txt
您的代码不会将匹配的数字与范围进行比较。
此外,您在最后一个条目后无端地打印了一个逗号。
试试这个。
perl -ne '$sep = ""; while (/(rate(\d+))/g ) {
if ( >= 2 and <= 5) {
print "$sep"; $sep=", ";
}
}
print "\n" if $sep' num_range.txt
另请注意 \d+
如何用于匹配 rate
之后的任何数字并提取到单独的数字比较中。这在孤立的情况下有点笨拙,但很容易适应不同的数字范围。
解释您的代码为何不起作用:
/rate(\d){2,5}/g
这与您认为的不同。 {x,y}
语法定义前一个字符串出现的 次 。
所以这匹配“字符串 'rate' 后跟 2 到 5 位数字”。这与您的数据中的任何内容都不匹配。
这样就可以了:
perl -anE '@rates=();while(/rate(\d+)/g){push @rates,$& if >=2 && <=15}say"@rates" if @rates' file.txt
输出:
rate2 rate3 rate4 rate5
rate2 rate3 rate4
rate2 rate3 rate4
一个简单的方法
perl -wnE'
print join",", grep { /rate([0-9]+)/ and >= 2 and <= 5 } split /\s*,\s*/
' file
硬编码关键字rate
和限制(2
和5
)当然可以是从输入设置的变量
我有一个像
这样的文件$ cat num_range.txt
rate1, rate2, rate3, rate4, rate5
pay1, pay2, rate1, rate2, rate3, rate4
rev1, rev2
rate2, rate3, rate4
我需要通过匹配前缀和数字范围来过滤逗号分隔的行。 例如 - 如果输入是“rate”并且范围是 2 到 5,那么我应该得到
rate2, rate3, rate4, rate5
rate2, rate3, rate4
rate2, rate3, rate4
如果是5比10,那我应该得到
rate5
当我使用 perl -ne ' while ( /rate(\d)/g ) { print "$&," } ; print "\n" ' num_range.txt
时,我得到了前缀的所有匹配项,
但是下面一个不行。
perl -ne ' while ( /rate(\d){2,5}/g ) { print "$&," } ; print "\n" ' num_range.txt
您的代码不会将匹配的数字与范围进行比较。
此外,您在最后一个条目后无端地打印了一个逗号。
试试这个。
perl -ne '$sep = ""; while (/(rate(\d+))/g ) {
if ( >= 2 and <= 5) {
print "$sep"; $sep=", ";
}
}
print "\n" if $sep' num_range.txt
另请注意 \d+
如何用于匹配 rate
之后的任何数字并提取到单独的数字比较中。这在孤立的情况下有点笨拙,但很容易适应不同的数字范围。
解释您的代码为何不起作用:
/rate(\d){2,5}/g
这与您认为的不同。 {x,y}
语法定义前一个字符串出现的 次 。
所以这匹配“字符串 'rate' 后跟 2 到 5 位数字”。这与您的数据中的任何内容都不匹配。
这样就可以了:
perl -anE '@rates=();while(/rate(\d+)/g){push @rates,$& if >=2 && <=15}say"@rates" if @rates' file.txt
输出:
rate2 rate3 rate4 rate5
rate2 rate3 rate4
rate2 rate3 rate4
一个简单的方法
perl -wnE'
print join",", grep { /rate([0-9]+)/ and >= 2 and <= 5 } split /\s*,\s*/
' file
硬编码关键字rate
和限制(2
和5
)当然可以是从输入设置的变量