如何在 perl 正则表达式中排除 0-9
How to exclude 0-9 in perl regex
在比较中,我试图排除以单个数字结尾的字符串,但无法正常工作。
鉴于:
@drives = ("sda", "sda1", "sda2", "sdb", "sdb1", "dm", "dm-0");
for $part (@drives)
{
if ($part =~ /sd.[^0-9]/)
{
print "\tBase: $part\n";
}
}
正则表达式 /sd.[^0-9]/
应该只匹配 sda 和 sdb。输出应该是:
Base: sda
Base: sdb
正则表达式看起来不错....为什么不起作用?
这一次正则表达式问题的答案很简单!
你的表达式 /sd.[^0-9]/
将 return 匹配 if sd
,后跟除换行符外的任何字符,后跟除 ASCII 之外的任何字符0
到 9
出现在 字符串中的任意位置
您必须锚定您的模式到字符串的开头和结尾以坚持 sd
出现在开头,非数字字符出现在字符串的开头结尾。您还应该使用 .*
以允许 零个或多个 个中间字符
这个程序显示了结果
use strict;
use warnings 'all';
my @drives = qw/ sda sda1 sda2 sdb sdb1 dm dm-0 /;
for my $part ( @drives ) {
if ( $part =~ /^sd.*[^0-9]$/ ) {
print "\tBase: $part\n";
}
}
产出
Base: sda
Base: sdb
请注意,这样写测试可能会更容易、更清晰
if ( $part =~ /^sd/ and $part =~ /[^0-9]$/ ) {
print "\tBase: $part\n";
}
你的正则表达式将无法工作,因为你的正则表达式试图匹配四个字符。
使用负面展望来做到这一点
@drives = ("sda", "sda1", "sda2", "sdb", "sdb1", "dm", "dm-0");
for $part (@drives)
{
if ($part =~m/sd.(?!\d+)/)
{
print "\tBase: $part\n";
}
}
使用带替换的 grep 而不是 for
@drives = ("sda", "sda1", "sda2", "sdb", "sdb1", "dm", "dm-0");
my @ac = grep{ s/(sd.)(?!\d)/\tBase : \n/; } @drives;
print @ac;
print "\n";
在比较中,我试图排除以单个数字结尾的字符串,但无法正常工作。
鉴于:
@drives = ("sda", "sda1", "sda2", "sdb", "sdb1", "dm", "dm-0");
for $part (@drives)
{
if ($part =~ /sd.[^0-9]/)
{
print "\tBase: $part\n";
}
}
正则表达式 /sd.[^0-9]/
应该只匹配 sda 和 sdb。输出应该是:
Base: sda
Base: sdb
正则表达式看起来不错....为什么不起作用?
这一次正则表达式问题的答案很简单!
你的表达式 /sd.[^0-9]/
将 return 匹配 if sd
,后跟除换行符外的任何字符,后跟除 ASCII 之外的任何字符0
到 9
出现在 字符串中的任意位置
您必须锚定您的模式到字符串的开头和结尾以坚持 sd
出现在开头,非数字字符出现在字符串的开头结尾。您还应该使用 .*
以允许 零个或多个 个中间字符
这个程序显示了结果
use strict;
use warnings 'all';
my @drives = qw/ sda sda1 sda2 sdb sdb1 dm dm-0 /;
for my $part ( @drives ) {
if ( $part =~ /^sd.*[^0-9]$/ ) {
print "\tBase: $part\n";
}
}
产出
Base: sda
Base: sdb
请注意,这样写测试可能会更容易、更清晰
if ( $part =~ /^sd/ and $part =~ /[^0-9]$/ ) {
print "\tBase: $part\n";
}
你的正则表达式将无法工作,因为你的正则表达式试图匹配四个字符。
使用负面展望来做到这一点
@drives = ("sda", "sda1", "sda2", "sdb", "sdb1", "dm", "dm-0");
for $part (@drives)
{
if ($part =~m/sd.(?!\d+)/)
{
print "\tBase: $part\n";
}
}
使用带替换的 grep 而不是 for
@drives = ("sda", "sda1", "sda2", "sdb", "sdb1", "dm", "dm-0");
my @ac = grep{ s/(sd.)(?!\d)/\tBase : \n/; } @drives;
print @ac;
print "\n";