Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape @ in Perl regex

Tags:

regex

perl

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 @?

like image 259
Matias Barrios Avatar asked Aug 08 '18 03:08

Matias Barrios


People also ask

How do you escape a regular expression in Perl?

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.

How do you escape a character in regex?

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).

Where can I find the documentation about Perl regular expressions?

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.

How many characters can you escape in a regular expression?

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'.


1 Answers

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.

like image 55
blhsing Avatar answered Sep 28 '22 14:09

blhsing