Expert Refresh



Search and replace
Text to html

0.0% 100%
0 pages 58 questions
1) Perl syntax to match a regex

2) Are nested parentheses for grouping permitted in Perl?

3) How do you group and non-capture regex in Perl?

Perl uses regex in many ways, the simplest being to check if a regex matches text held in a variable. The m/../ surrounding the regex tells Perl what to do with it. The surrounding ^$ ensures that the entire $phone contains only digits.
$phone = "0728824242"; if ($phone =~ m/^[0-9]+$/) { print "only digits"; } Nesting parentheses
With advanced programming languages like Perl, regex use can become quite intertwined with the logic of the rest of the program.
$temp = "-98.6 F"; if($temp =~ m/^([-+]?[0-9]+(.[0-9]*)?) ([CF])$/) { print "n $1"; #98.6 print "n $2"; #.6 print "n $3"; #F } Non-capturing parentheses
Wouldn't it be better if there were a type of parentheses that we could use for grouping which didn't involve the overhead (and possible confusion) of capturing and saving text to a variable that we never intend to use? Perl, and some other regex flavors, do provide a way to do this. You can use the special notation (?: ), which group but do not capture. This use of "?:" has no relation to the optional "?" metacharacter.
$temp = "-98.6 F"; if($temp =~ m/^([-+]?[0-9]+(?:.[0-9]*)?) (?:[CF])$/) { // Look at (?: parts print "n $1"; #-98.6 print "n $2"; #nothing - not captured print "n $3"; #nothing } Benefits
The benefits of this are twofold. The match process is more efficient, and may be less confusing later to someone reading the code who might otherwise be left wondering about the exact nature of each set of parentheses.