I want to detect the presence of certain characters like @ # $ % \ / in a Perl string. Can anyone suggest a regex for this. I tried few but it is not working.
我想检测某些字符的存在,比如@ # $ % \ /在Perl字符串中。有人能给我推荐一个regex吗?我试了几次,但没有成功。
=~ /(\W@\W#\W%\W*)/)
=~ /(@|#|%|*)/)
I tried these but it is not working.
我试过了,但没用。
Can anyone suggest where i am going wrong?
谁能告诉我哪里出错了吗?
3 个解决方案
#1
2
You were on the right track with your second attempt, but you forgot to escape characters that have a special meaning in regex patterns.
您在第二次尝试时走对了方向,但是您忘记了转义在regex模式中具有特殊意义的字符。
/\@|#|\$|%|\\|\// # or m{\@|#|\$|%|\\|/}
However, it would be more efficient to use a character class.
但是,使用字符类会更有效。
/[\@#\$%\\//]/ # or m{[\@#\$%\\/]}
If you're ok with checking for any non-word characters, you can use
如果可以检查任何非单词字符,可以使用
/\W/
A safer approach is usually to specify the characters you want to allow, and exclude everything else. For example,
更安全的方法通常是指定要允许的字符,并排除其他所有字符。例如,
/[^\w]/ # Only allow word characters.
or
或
/[^a-zA-Z0-9_]/ # Only allow unaccented latin letters, "european" digits, and underscore.
#2
1
This should work:
这应该工作:
=~ /[@#$%\/]/
if one of the character is included in the string it will detected
如果一个字符包含在字符串中,它将被检测到
my $s = "@";
if ($s =~ /[@#\$\%\/]/) {
print "have it";
}
#3
0
You can use quotemeta
. For example:
您可以使用quotemeta。例如:
my $chars = '@#$%\/';
my ($regex) = map { qr /$_/ } join '|', map {quotemeta} split //, $chars;
#1
2
You were on the right track with your second attempt, but you forgot to escape characters that have a special meaning in regex patterns.
您在第二次尝试时走对了方向,但是您忘记了转义在regex模式中具有特殊意义的字符。
/\@|#|\$|%|\\|\// # or m{\@|#|\$|%|\\|/}
However, it would be more efficient to use a character class.
但是,使用字符类会更有效。
/[\@#\$%\\//]/ # or m{[\@#\$%\\/]}
If you're ok with checking for any non-word characters, you can use
如果可以检查任何非单词字符,可以使用
/\W/
A safer approach is usually to specify the characters you want to allow, and exclude everything else. For example,
更安全的方法通常是指定要允许的字符,并排除其他所有字符。例如,
/[^\w]/ # Only allow word characters.
or
或
/[^a-zA-Z0-9_]/ # Only allow unaccented latin letters, "european" digits, and underscore.
#2
1
This should work:
这应该工作:
=~ /[@#$%\/]/
if one of the character is included in the string it will detected
如果一个字符包含在字符串中,它将被检测到
my $s = "@";
if ($s =~ /[@#\$\%\/]/) {
print "have it";
}
#3
0
You can use quotemeta
. For example:
您可以使用quotemeta。例如:
my $chars = '@#$%\/';
my ($regex) = map { qr /$_/ } join '|', map {quotemeta} split //, $chars;