Im using perl to match a password against a regex in a bash script.
While testing the regex for the password, I got to this problem:
This works :
perl -e 'if ( "Bomba\@2071" =~ /^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8,}$/ ) { print 1; } '
While this never matches :
perl -e 'if ( "Bomba@2071" =~ /^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8,}$/ ) { print 1; } '
As you can notice, it works because I escape the @ symbol. I had never seen something like this in another programming languages and after being stuck with this for over an hour, I found the reason by mere chance.
So, my question is, Whats going on here? Why do I need to escape an odd character like @?
regular expression is feature Code language: Perl (perl) If you want to match a pattern that contains a forward slash (/) character, you have to escape it using a backslash () character. You can also use a different delimiter if you precede the regular expression with the letter m, the letter m stands for match.
For example, a common way to escape any single-byte character in a regex is to use 'hex escaping'. For example, the hexadecimal equivalent of the character 'a' when encoded in ASCII or UTF-8 is '\x61'. Hexadecimal escaping is not supported by all regular expression implementations (most notably POSIX-based implementations).
The top level documentation about Perl regular expressions is found in perlre. This document describes all backslash and escape sequences. After explaining the role of the backslash, it lists all the sequences that have a special meaning in Perl regular expressions (in alphabetical order), then describes each of them.
Here are the 14 characters that you'll need to be careful about escaping in a regular expression (outside a character class): [ ] \ ^ * + ? { } | ( ) $ . Most regular expression engines support more than one way to escape many characters. For example, a common way to escape any single-byte character in a regex is to use 'hex escaping'.
This is because @
in perl denotes to an array variable, so without escaping it what follows would be interpreted as an array variable.
Besides escaping @
, you can also use single quotes instead of double quotes, e.g. 'Bomba@2071'
, so that the string would not be subject to interpretation, although in this case it would create a new problem since you're using single quotes to quote the entire perl source in a shell command. So stick to escaping in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With