How to have a variable as regex in Perl - regex

I think this question is repeated, but searching wasn't helpful for me.
my $pattern = "javascript:window.open\('([^']+)'\);";
$mech->content =~ m/($pattern)/;
print $1;
I want to have an external $pattern in the regular expression. How can I do this? The current one returns:
Use of uninitialized value $1 in print at main.pm line 20.

$1 was empty, so the match did not succeed. I'll make up a constant string in my example of which I know that it will match the pattern.
Declare your regular expression with qr, not as a simple string. Also, you're capturing twice, once in $pattern for the open call's parentheses, once in the m operator for the whole thing, therefore you get two results. Instead of $1, $2 etc. I prefer to assign the results to an array.
my $pattern = qr"javascript:window.open\('([^']+)'\);";
my $content = "javascript:window.open('something');";
my #results = $content =~ m/($pattern)/;
# expression return array
# (
# q{javascript:window.open('something');'},
# 'something'
# )

When I compile that string into a regex, like so:
my $pattern = "javascript:window.open\('([^']+)'\);";
my $regex = qr/$pattern/;
I get just what I think I should get, following regex:
(?-xism:javascript:window.open('([^']+)');)/
Notice that it it is looking for a capture group and not an open paren at the end of 'open'. And in that capture group, the first thing it expects is a single quote. So it will match
javascript:window.open'fum';
but not
javascript:window.open('fum');
One thing you have to learn, is that in Perl, "\(" is the same thing as "(" you're just telling Perl that you want a literal '(' in the string. In order to get lasting escapes, you need to double them.
my $pattern = "javascript:window.open\\('([^']+)'\\);";
my $regex = qr/$pattern/;
Actually preserves the literal ( and yields:
(?-xism:javascript:window.open\('([^']+)'\);)
Which is what I think you want.
As for your question, you should always test the results of a match before using it.
if ( $mech->content =~ m/($pattern)/ ) {
print $1;
}
makes much more sense. And if you want to see it regardless, then it's already implicit in that idea that it might not have a value. i.e., you might not have matched anything. In that case it's best to put alternatives
$mech->content =~ m/($pattern)/;
print $1 || 'UNDEF!';
However, I prefer to grab my captures in the same statement, like so:
my ( $open_arg ) = $mech->content =~ m/($pattern)/;
print $open_arg || 'UNDEF!';
The parens around $open_arg puts the match into a "list context" and returns the captures in a list. Here I'm only expecting one value, so that's all I'm providing for.
Finally, one of the root causes of your problems is that you do not need to specify your expression in a string in order for your regex to be "portable". You can get perl to pre-compile your expression. That way, you only care what instructions the characters are to a regex and not whether or not you'll save your escapes until it is compiled into an expression.
A compiled regex will interpolate itself into other regexes properly. Thus, you get a portable expression that interpolates just as well as a string--and specifically correctly handles instructions that could be lost in a string.
my $pattern = qr/javascript:window.open\('([^']+)'\);/;
Is all that you need. Then you can use it, just as you did. Although, putting parens around the whole thing, would return the whole matched expression (and not just what's between the quotes).

You do not need the parentheses in the match pattern. It will match the whole pattern and return that as $1, which I am guess is not matching, but I am only guessing.
$mech->content =~ m/$pattern/;
or
$mech->content =~ m/(?:$pattern)/;
These are the clustering, non-capturing parentheses.
The way you are doing it is correct.

The solutions have been already given, I'd like to point out that the window.open call might have multiple parameters included in "" and grouped by comma like:
javascript:window.open("http://www.javascript-coder.com","mywindow","status=1,toolbar=1");
There might be spaces between the function name and parentheses, so I'd use a slighty different regex for that:
my $pattern = qr{
javascript:window.open\s*
\(
([^)]+)
\)
}x;
print $1 if $text =~ /$pattern/;
Now you have all parameters in $1 and can process them afterwards with split /,/, $stuff and so on.

It reports an uninitialized value because $1 is undefined. $1 is undefined because you have created a nested matching group by wrapping a second set of parentheses around the pattern. It will also be undefined if nothing matches your pattern.

Related

Regular expression chaining/mixing in perl

Consider the following:
my $p1 = "(a|e|o)";
my $p2 = "(x|y|z)";
$text =~ s/($p1)( )[$p2]([0-9])/some action to be done/g;
Is the regular expression pattern in string form equal to the concatenation of the elements in the above? That is, can the above can be written as
$text =~ s/((a|e|o))( )[(x|y|z)]([0-9])/ some action to be done/g;
Well, yes, variables in a pattern get interpolated into the pattern, in a double-quoted context, and the expressions you show are equivalent. See discussion in perlretut tutorial.
(I suggest using qr operator for that instead. See discussion of that in perlretut as well.)
But that pattern clearly isn't right
Why those double parenthesis, ((a|e|o))? Either have the alternation in the variable and capture it in the regex
my $p1 = 'a|e|o'; # then use in a regex as
/($p1)/ # gets interpolated into: /(a|e|o)/
or indicate capture in the variable but then drop parens in the regex
my $p1 = '(a|e|o)'; # use as
/$p1/ # (same as above)
The capturing parenthesis do their job in either way and in both cases a match ( a or e or o) is captured into a suitable variable, $1 in your expression since this is the first capture
A pattern of [(x|y|z)] matches either one of the characters (, x, |,... (etc) -- that [...] is the character class, which matches either of the characters inside (a few have a special meaning). So, again, either use the alternation and capture in your variable
my $p2 = '(x|y|z)'; # then use as
/$p2/
or do it using the character class
my $p2 = 'xyz'; # and use as
/([$p2])/ # --> /([xyz])/
So altogether you'd have something like
use warnings;
use strict;
use feature 'say';
my $text = shift // q(e z7);
my $p1 = 'a|e|o';
my $p2 = 'xyz';
$text =~ s/($p1)(\s)([$p2])([0-9])/replacement/g;
say $_ // 'undef' for $1, $2, $3, $4;
I added \s instead of a literal single space, and I capture the character-class match with () (the pattern from the question doesn't), since that seems to be wanted.
Neither snippets are valid Perl code. They are therefore equivalent, but only in the sense that neither will compile.
But say you have a valid m//, s/// or qr// operator. Then yes, variables in the pattern would be handled as you describe.
For example,
my $p1 = "(a|e|o)";
my $p2 = "(x|y|z)";
$text =~ /($pl)( )[$p2]([0-9])/g;
is equivalent to
$text =~ /((a|e|o))( )[(x|y|z)]([0-9])/g;
As mentioned in an answer to a previous question of yours, (x|y|z) is surely a bug, and should be xyz.

perl script not extracting only path (regex)

I have this regex expression
($oldpath = $_) =~ m/^\/(.+\/)*/;
This is the input:
/cd-lib/mp3/rock/LittleFeat/Dixie_Chicken/110-lafayette_railroad.mp3
But the output is:
/cd-lib/mp3/rock/LittleFeat/Dixie_Chicken/110-lafayette_railroad.mp3
When it should be:
/cd-lib/mp3/rock/LittleFeat/Dixie_Chicken/
Thanks in advance. :)
What do you mean by "output"? $1 contains
cd-lib/mp3/rock/LittleFeat/Dixie_Chicken/
which is almost what you wanted (it just misses the leading /).
You assigned $_ to $oldpath, than matched it against a regex. It doesn't change either $_ or $oldpath.
The canonical way is
my ($match) = m/^\/(.+\/)*/;
or rather (to prevent the leaning toothpick syndrome)
my ($match) = m{^/(.+/)*};
i.e. running the match in list context returns the matching capture groups, and the first one is assinged to $match.

print the matched word in perl regex

I need to print all my matched strings from a stored line in perl. I have seen various posts on this
Print the matched string using perl
Perl Regex - Print the matched value
and I experimented to first try to print the first word. But I get a build error
Use of uninitialized value $1 in concatenation (.) or string at rg.pl line 10.
I have tried with split and arrays and it works, but while printing $1, it throws error.
My code is here
#!/usr/bin/perl/
use warnings;
use strict;
#my $line = "At a far distance near the bar, was a parked car. Star were shining in the night. The boy in the car had scar and he was at war with his enemy. \n";
my $line = "At a far distance near the bar, was a parked car. \n";
if($line =~ /[a-z]ar/gi)
{ print "$1 \n"; }
$_ = $line;
I want my output for this code to be
far
and subsequently print all the words containing ar,
far
near
bar
parked
car
I even tried changing my code, as below but that didnt work, same error
if($line =~ /[a-z]ar/gi) {
my $match = $1;
print "$match \n"; }
First, you didn't capture anything, which is how $n variables are populated. Put parenthesis around what you want to be captured into $1
if ($line =~ /([a-z]ar)i/) { print "$1\n" }
I've removed the /g which is unneeded (and with potential for trouble†) here.
Next, your pattern requires and captures one letter followed by literal ar, no more no less. That won't capture near, nor will it capture parked (it'll get par only). It will not even match a word that starts with ar, since it requires that there is a letter before ar. You need to use quantifiers, to tell it how many times to match a letter. And you also want to find all matches.
One way is to scoop them all up by providing the list context and /g (global) modifier
my #words = $line =~ /([a-z]*ar[a-z]*)/gi;
print "$_\n" for #words;
The [a-z]* means to match a letter, zero-or-more times. So an optional string of letters. We also added an optional string of letters after ar. The /g makes it continue through the string after a match, to find all such patterns. In the list context the list of matches is returned.
Or, you can match in scalar context like in the first example, but in a while loop
while ($line =~ /([a-z]*ar[a-z]*)/gi) { print "$1\n" }
Here /g does something different. It matches a pattern once and returns true, the while condition is true and we print. Then it comes back and looks for a match from where it matched previously ... and keeps doing this until there are no more matches.
This is complex behavior altogether. From Regexp Quote-Like Operators in perlop
The /g modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.
In scalar context, each execution of m//g finds the next match, returning true if it matches, and false if there is no further match. [...]
Read about this in more detail and in a tutorial manner in perlretut, under "Global matching."
† Note on using /g modifier in scalar context
I've used that above, in while (/.../g), what is a very common way to hop over all occurrences of the pattern in a string, each time giving us control in the while body.
While this use is intended and idiomatic, the use of /g in scalar context can bring subtle trouble when not in the loop condition: the next regex with /g on this variable will continue from the previous match, not from the string's beginning, what may be unexpected.
That "next regex" may also simply be that same expression -- in the next pass of some larger loop in which our expression happens to be, and this holds across function calls as well. Consider
use warnings;
use strict;
use feature 'say';
my $s = q(one two three);
sub func { say $1 if $_[0] =~ /(\w+)/g }; # /g may be of great consequence!
for (1..4) {
# ... perhaps much, much later ...
func($s);
}
This loop prints lines one, then two, then three, and that's that. This (working) example is so bare bones that it is artificial bit I hope that it conveys that /g in scalar context may surprise.
For one thing, it is not uncommon to see /g on a regex in an if condition being plain wrong.
For multiple matches, use a while loop. Also, I surrounded the quantity you want to capture with parentheses to indicate that it is a capture group.
while ($line =~ /([a-z]*ar[a-z]*)/gi ) {
print "$1 \n";
}

Using regex to fetch a value

I have a string:
set a "ODUCTP-1-1-1-2P1"
regexp {.*?\-(.*)} $a match sub
I expect the value of sub to be 1-1-1-2P1
But I'm getting empty string. Can any one tell me how to properly use the regex?
The problem is that the non-greediness of the .*? is leaking over to the .* later on, which is a feature of the RE engine being used (automata-theoretic instead of stack-based).
The simplest fix is to write the regular expression differently.
Because Tcl has unanchored regular expressions (by default) and starts matches as soon as it can, a greedy match from the first - to the end of the string is perfect (with sub being assigned everything after the -). That's a very simple RE: -(.*). To use that, you do this:
regexp -- {-(.*)} $a match sub
Note the --; it's needed here because the regular expression starts with a - symbol and is otherwise confused as weird (and unsupported) option. Apart from that one niggle, it's all entirely straight-forward.
$str = "ODUCTP-1-1-1-2P1";
$str =~ s/^.*?-//;
print $str;
or:
$str =~ /^.*?-(.*)$/;
print $1;

Perl match only returning "1". Booleans? Why?

This has got to be obvious but I'm just not seeing it.
I have a documents containing thousands of records just like below:
Row:1 DATA:
[0]37755442
[1]DDG00000010
[2]FALLS
[3]IMAGE
[4]Defect
[5]3
[6]CLOSED
I've managed to get each record separated and I'm now trying to parse out each field.
I'm trying to match the numbered headers so that I can pull out the data that succeeds them but the problem is that my matches are only returning me "1" when they succeed and nothing if they don't. This is happening for any match I try to apply.
For instance, applied to a simple word within each record:
my($foo) = $record=~ /Defect/;
print STDOUT $foo;
prints out out a "1" for each record if it contains "Defect" and nothing if it contains something else.
Alternatively:
$record =~ /Defect/;
print STDOUT $1;
prints absolutely nothing.
$record =~ s/Defect/Blefect/
will replace "Defect" with "Blefect" perfectly fine on the other hand.
I'm really confused as to why the returns on my matches are so screwy.
Any help would be much appreciated.
You need to use capturing parentheses to actually capture:
if ($record =~ /(Defect)/ ) {
print "$1\n";
}
I think what you really want is to wrap the regex in parentheses:
my($foo) = $record=~ /(Defect)/;
In list context, the groups are returned, not the match itself. And your original code has no groups.
The =~ perl operator takes a string (left operand) and a regular expression (right operand) and matches the string against the RE, returning a boolean value (true or false) depending on whether the re matches.
Now perl doesn't really have a boolean type -- instead every value (of any type) is treated as either 'true' or 'false' when in a boolean context -- most things are 'true', but the empty string and the special 'undef' value for undefined things are false. So when returning a boolean, it generall uses '1' for true and '' (empty string) for false.
Now as to your last question, where trying to print $1 prints nothing. Whenever you match a regular expression, perl sets $1, $2 ... to the values of parenthesized subexpressions withing the RE. In your example however, there are NO parenthesized sub expressions, so $1 is always empty. If you change it to
$record =~ /(Defect)/;
print STDOUT $1;
You'll get something more like what you expect (Defect if it matches and nothing if it doesn't).
The most common idiom for regexp matching I generally see is something like:
if ($string =~ /regexp with () subexpressions/) {
... code that uses $1 etc for the subexpressions matched
} else {
... code for when the expression doesn't match at all
}
From perlop, Quote and Quote-Like operators [bits in brackets added by me]:
/PATTERN/msixpodualgc
Searches a string for a pattern match, and in scalar context returns true [1] if it succeeds, false [undef] if it fails.
(Looking at the section on s/// will also be useful ;-)
Perl just doesn't have a discreet boolean type or true/false aliases so 1 and undef are often used: however, it could very well could be other values without making the documentation incorrect.
$1 will never be defined because there is no capture group: perhaps $& (aka $MATCH) is desired? (Or better, change the regular expression to have a capture group ;-)
Happy coding.
my($foo) = $record=~ /Defect/;
print STDOUT $foo;
Rather than this you should do
$record =~ /Defect/;
my $foo = $&; # Matched portion of the $record.
As your goal seems to be to get the matched portion.
The return value is true/false indicating if match was successful or not.
You may find http://perldoc.perl.org/perlreref.html handy.
If you want the result of a match as "true" or "false", then do the pattern match in scalar context. That's what you did in your first example. You performed a pattern match and assigned the result to the scalar my($foo). So $foo got a "true" or "false" value.
But if you want to capture the text that matched a part of your pattern, use grouping parentheses and then check the corresponding $ variable. For example, consider the expression:
$record =~ /(.*)ing/
A match on the word "speaking" will assign "speak" to $1, "listening" will assign "listen" to $1, etc. That's what you are trying to do in your second example. The trouble is that you need to add in the grouping parentheses. "$record =~ /Defect/" will assign nothing to $1 because there are no grouping parentheses in the pattern.