I have text in the form:
Name=Value1
Name=Value2
Name=Value3
Using Perl, I would like to match /Name=(.+?)/
every time it appears and extract the (.+?) and push it onto an array. I know I can use $1
to get the text I need and I can use =~
to perform the regex matching, but I don't know how to get all matches.
To count the number of regex matches, call the match() method on the string, passing it the regular expression as a parameter, e.g. (str. match(/[a-z]/g) || []). length . The match method returns an array of the regex matches or null if there are no matches found.
m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.
The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match.
The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”. This match is zero-length. There are three different positions that qualify as word boundaries: Before the first character in the string, if the first character is a word character.
A m//g
in list context returns all the captured matches.
#!/usr/bin/perl use strict; use warnings; my $str = <<EO_STR; Name=Value1 Name=Value2 Name=Value3 EO_STR my @matches = $str =~ /=(\w+)/g; # or my @matches = $str =~ /=([^\n]+)/g; # or my @matches = $str =~ /=(.+)$/mg; # depending on what you want to capture print "@matches\n";
However, it looks like you are parsing an INI style configuration file. In that case, I will recommend Config::Std.
my @values; while(<DATA>){ chomp; push @values, /Name=(.+?)$/; } print join " " => @values,"\n"; __DATA__ Name=Value1 Name=Value2 Name=Value3
The following will give all the matches to the regex in an array.
push (@matches,$&) while($string =~ /=(.+)$/g );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With