2

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.

=~ /(\W@\W#\W%\W*)/)
=~ /(@|#|%|*)/) 

I tried these but it is not working.

Can anyone suggest where i am going wrong?

Jens
  • 67,715
  • 15
  • 98
  • 113
dev_k2.0
  • 39
  • 1
  • 1
  • 4

3 Answers3

4

You were on the right track with your second attempt, but you forgot to escape characters that have a special meaning in regex patterns.

/\@|#|\$|%|\\|\//       # 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.
ikegami
  • 367,544
  • 15
  • 269
  • 518
1

This should work:

=~ /[@#$%\/]/

if one of the character is included in the string it will detected

my $s = "@";
if ($s =~ /[@#\$\%\/]/) {
        print "have it";
}
Borodin
  • 126,100
  • 9
  • 70
  • 144
Jens
  • 67,715
  • 15
  • 98
  • 113
  • It is detecting only the first character. Try with # it will not work – dev_k2.0 Apr 24 '17 at 10:13
  • $% is treated as a variable (interpolating '0'), and the backslash escapes the forward slash. try `/[\@#\$%\\\/]/` – ysth Apr 24 '17 at 10:16
  • try this. It is not working at my end my $s = "lj2dm%"; if ($s =~ /[@#$%\/]/) { print "have it \n"; } – dev_k2.0 Apr 24 '17 at 10:21
  • @dev_k2.0 The % sign must be escaped. See my edited answer – Jens Apr 24 '17 at 10:25
  • No, `%` doesn't need to be escaped, though there's no harm (except to readability) in escaping it. (I'm not the downvoter.) – ikegami Apr 24 '17 at 19:30
0

You can use quotemeta. For example:

my $chars = '@#$%\/';
my ($regex) = map { qr /$_/ } join '|', map {quotemeta} split //, $chars;
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174