Perl Regex named capture variables

Simple example to extract, protocol, server and domain from a given URL:

Our Result:

Regular expression

A regular expression is a search pattern, its very often used in the programming language Perl, but it is used in other programming languages too or Text editors.

 

Meta characters

char meaning
^ defines the end of the matching String
$ defines the end of the matching String
. matches any character but not newline
* matches from 0 to infinity times
+ matches from 1 to infinity times
? matches 0 or 1 times
{} matches exact the given number or range
| logical or operator
() makes a group to store the result
[] makes a character matching group

 

Matches

\t tabulator
\n new line
\r return (CR)
\w matches from a-z,A-Z,0-9 and “_”.
\W matches nothing from a-z,A-Z,0-9 and “_”.
\s matches space, tab and newline
\S matches nothing from space, tab and newline
\d matches from 0-9
\D matches nothing from 0-9

 

Examples

This matches every string that starts with an “a”.

This pattern matches every string that end with an “a”.

This regex would match “schools” and “school”.

Would match every string with the length between 3 and 4.

This also would match “schools” and “school”.

On this “this is an ‘test’.” the pattern would store “test”.

This regex matches every combination from “a”,”c” and “o” like the word “coca”.

 

For testing Regex you could test the JavaScript Regex tester.

JavaScript Regex tester

This is a little JavaScript Regex tester, just write your Regex as example "\d" or "\w" and a test string like "123abc". It is more like an example as an real use function, but you can see how it works and handle the matches. Try it:

Matches:
Code:

Perl Regex on different lines

This little example shows how to use a regex on different lines: As Result we get this:

Check password with Perl

This little Perl-Script checks if we use a password longer than 9 characters, 2 lower-case digits, 2 upper-case digits, 2 numbers and 2 special chars. And our result looks like: Now we could check our passwords.

Benchmark in Perl – replace

if you want to check whats the fastest way to replace a string in Perl you could use the Benchmark-Module.I compared 4 different ways  : the result looks like: Always check you sub results (Line 1-5) and make more test cases, at the first case (Line 6) we see that for single character the best solution is to use regex.If you want to replace a longer string better use a C function.But in both cases its better to use the /o flag for regex to optimize, but then you cant interpolate a string in to the regex.And if you only want to replaxe use tr its the fastest.