print the matched word in perl regex - 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";
}

Related

Pre-compiled regex with special characters matching

I'm trying to match if a word such as *FOO (* as a normal character) is in a line. My input is a C++ source code. I need to use a pre-compiled regex for this due to program flow requirements, so I tried the following:
$pattern = qr/[^a-zA-Z](\*FOO)[^a-zA-Z]|^\s*(\*FOO)[^a-zA-Z]/;
And I use it like this:
if ($line =~ m/$pattern/) { ... }
It works and catches lines containing *FOO such as hey *FOO.BAR but also matches lines such as:
//FOO programming using stuff and things
which I want to ignore. What am I missing? Is \* not the right way to escape * in a pre-compiled regex in perl? If *FOO is stored in $word and the pattern looks like this:
$pattern = qr/[^a-zA-Z](\\$word)[^a-zA-Z]|^\s*(\\$word)[^a-zA-Z]/;
Is that different from the previous pattern? Because I tried both and the result seems to be the same.
I found a way to bypass this problem by removing the first char of $word and escaping * in the pattern, but if $word = "**.?FOO" for example, how do I create a qr// with $word so that all the meta-characters are escaped?
You do need to escape the *. One way to do it is by the quotemeta \Q operator:
use warnings;
use strict;
my $qr = qr/\Q*FOO/;
while (<DATA>) { print if /$qr/ }
__DATA__
//FOO programming using stuff and things
hey *FOO.BAR
Note that this escapes all ASCII non-"word" characters through the rest of the pattern. If you need to limit its action to only a part of the pattern then stop it using \E. Please see linked docs.
The above determines whether *FOO is in the line, regardless of whether it is a word or a part of one. It is not clear to me which is needed. Once that is specified the pattern can be adjusted.
Note that /\*FOO/ works, too. What you tried failed probably because of all the rest that you are trying to match, which purpose I do not understand. If you only need to detect whether the pattern is present the above does it. if there is a more specific requirement please clarify.
As for the examples: for me that string //FOO... is not matched by the main (first) $pattern you show. The second one won't interpolate $word -- but is firstly much too convoluted. The regex can really tie one in nasty knots when pushed; I suggest to keep it simple as much as possible.
Question 1:
my $word = '*FOO';
my $pattern = qr/\\$word/;
is equivalent to
my $pattern = qr/\\*FOO/; # zero or more '\' followed by 'FOO'
The $word is simply interpolated as is.
To get something equivalent to
my $pattern = qr/\*FOO/;
you should use
my $word = '*FOO';
my $pattern = qr/\Q$word\E/;
By default, an interpolated variable is considered a mini-regular expression, meta characters in the variable such as *, +, ? are still interpreted as meta character. \Q...\E will add a backslash before any character not matching /[A-Za-z_0-9]/, thus any meta characters in the interpolated variable is interpreted as literal ones. Refer to perldoc.
Question 2
I tried
my $pattern = qr/[^a-zA-Z](\*FOO)[^a-zA-Z]|^\s*(\*FOO)[^a-zA-Z]/;
my $line = '//FOO programming using stuff and things';
if($line =~ m/$pattern/){
print "$&\n";
}
else{
print "No match!";
}
and it printed "No match!". I can't explain how you get it matched.

Regex to match hours and time

I'm still learning Perl regular expressions and I need to match a string that represents the time.
However there are instances where multiple times get entered. Instead of '9AM' I will sometimes get '9AM5PM' or '09AM05PM' and so on... Fortunately, It always starts with one or two numbers and ends with 'AM' or 'PM' (Upper and Lowercase)
Here's what I have so far:
$string =~ /^((([1-9])|(1[0-2]))*(A|P)M)$/i;
Any help would be greatly appreciated!
The only problem I can see with your own code is that the hours field is optional (because you use a *) but you don't say what issues you're having.
You do have a lot of unnecessary captures. Every part of the pattern that is enclosed in parentheses will capture the corresponding part of the target string in an internal variables called $1, $2 etc. Unless you really need those captures it is best to use non-capturing parentheses (?: ... ) instead of the plain ones ( ... ).
Character classes like [1-9] are a single entity and don't need enclosing in parentheses. You also haven't accounted for a leading zero on values less than ten, and you should use a character class [AP] instead of an alternation (?:A|P)
It looks like you need
/\d{1,2}[AP]M/i
But you don't say what you want to do with the times once you have found them.
This snippet of code demonstrates the functionality by putting all the times that it finds in a string into array #times and then printing it with space separators.
use strict;
use warnings;
for my $string (qw/ 9AM 9AM5PM 09AM05PM /) {
my #times = $string =~ /\d{1,2}[AP]M/ig;
print "#times\n";
}
output
9AM
9AM 5PM
09AM 05PM
If you really want to verify that the hour value is in range (are you likely to come across 35pm?) then you could write
my #times = $string =~ / (?: 1[012] | 0?[1-9] ) [AP]M /igx
Note that the /x modifier makes whitespace insignificant within regular expressions, so that it can be used to clarify the form of the pattern.
You can try something like:
$string =~ /^((0?\d|1[0-2])[AP]M)+$/i;
As you can see here. Or:
$string =~ /^((0?\d|1[0-2])[AP]M){1,2}$/i;
If you want it to be just up to 2 hours together.

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.

Regex to match suffixes to english words

I'm searching for the word "move" and i want to match "moved" as well when I print.
The way I'm going about this is:
if ($sentence =~ /($search_key)d$/i) {
$search_key = $search_keyd;
}
$subsentences[$i] =~ s/$search_key/ **$search_key** /i;
$subsentences[$i] =~ s/\b$parsewords[1]_\w+/ --$parsewords[1]--/i;
print "MATCH #$count\n",split(/_\S+/,$subsentences[$i]), "\n";
$count++;
This is part of a longer code so if anything is unclear let me know. The _ is because the words in the sentence are tagged (ex. I_NN move_VB to_PREP ....).
Where $search_keyd will be $search_key."d", which worked!
A nice addition would be to check if the word ended in e and therefore only a d would need to be appended. I'd guess it'd look something like this: e?$/d$
Even a general answer will suffice.
I'm new to Perl. So sorry if this is elementary. Thanks in advance!!!
If I understand you correctly, you want to search for "move" and add a highlight, but also include any variation of the basic word, such as "moves" "moved".
When you are replacing words in a text like this, you usually want to replace all the words, and then you need the /g operator on the regex, like so:
$subsentences[$i] =~ s/$search_key/ **$search_key** /ig
Also, you should make sure to not match partials of words. E.g. you want to match "move", but not perhaps "remove". For this, you can use \b to mark word boundry:
$subsentences[$i] =~ s/\b$search_key/ **$search_key** /ig
In order to match certain suffixes, you need a character class with valid characters or combination of characters. move[sd] will find "moves" and "moved". However, for a word like "jump", you would need to be a bit more specific: "jump(s|ed)". Note that [sd] can be replaced with (s|d). So barring any bad spelling in your text, you can get away with:
$subsentences[$i] =~ s/\b$search_key(s|d|ed)/ **$search_key$1** /ig
Note that $1 matches whatever is found inside the first matching parenthesis.
To find the number of matching words:
my $matches = $subsentences[$i] =~ s/\b$search_key(s|d|ed)/ **$search_key$1** /ig
If you want to be more specific with the suffixes, i.e. make it not match badly spelled words like "moveed", you'd need to do some special matching. Something like:
if ($search_key =~ /e$/i) { $suffix = '(s|d)' }
else { $suffix = '(s|ed)' }
my $matches = $subsentences[$i] =~ s/\b$search_key$suffix/ **$search_key$1** /ig
It can probably become very complicated the more search words you add.
Some help about regexes here
If what you want is to match all complete words which begin with your search term, i.e. 'move' matches 'move', 'moved', 'movers', etc, then you want to use a character class to detect the end of the word.
So, instead of:
if ($sentence =~ /($search_key)d$/i)
Try using:
if ($sentence =~ /($search_key\w*)\W$/i)
The \w* will match any number of standard word characters and the \W should prevent you from including other characters, such as whitespace or punctuation.

How to have a variable as regex in Perl

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.