Jae*_*ark 0 regex string perl compare
我在我的脚本中使用"=〜"来比较两个字符串(两个字符串的长度是相同的.)以允许不关心条件.如果一个角色是"." 在字符串中,忽略该字符进行比较.换句话说,它是部分匹配的情况.
comp_test.pl:
#!/usr/bin/perl
use strict;
use warnings;
my $a=".0.0..0..1...0..........0...0......010.1..........";
my $b="10.0..0..1...0..........0...0......010.1..........";
my $c=".0.0..0..1...0..........0...0......010.1..........";
if ($a =~ $b) {
print "a and b same\n";
}
if ($a =~ $c) {
print "a and c same\n";
}
Run Code Online (Sandbox Code Playgroud)
由于"."不关心条件,预期结果应该是"a和b相同"和"a和c相同".但是,目前,结果只是"a和c相同".请告诉我任何好的操作员或更改"." "x"可能有帮助吗?
这不是perl版本问题.你正在进行正则表达式匹配.左边的操作数=~是字符串,右边的操作数是应用于它的正则表达式.
这可以用于您正在进行的部分匹配,假设字符串长度相同并且正则表达式的每个字符与字符串的字符匹配,但仅限.于右侧的字符.如果正则表达式中有一个1或一个0($b在这种情况下$a =~ $b),则string($a)中必须有一个完全匹配的字符,而不是a ..
要进行您似乎想要做的部分匹配,您可以使用按位异或,如下所示:
sub partial_match {
my ($string_1, $string_2) = @_;
return 0 if length($string_1) != length($string_2);
# bitwise exclusive or the two strings together; where there is
# a 0 in one string and a 1 in the other, the result will be "\1".
# count \1's to get the number of mismatches
my $mismatches = ( $string_1 ^ $string_2 ) =~ y/\1//;
return $mismatches == 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
223 次 |
| 最近记录: |