Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all matches to a regular expression in Perl?

Tags:

regex

perl

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.

like image 498
Thomas Owens Avatar asked Nov 12 '09 16:11

Thomas Owens


People also ask

How do you find the number of matches in a regular expression?

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.

How do you get a matched string in Perl?

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.

What does =~ do in Perl?

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.

What is \b in Perl regex?

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.


3 Answers

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.

like image 190
Sinan Ünür Avatar answered Sep 29 '22 18:09

Sinan Ünür


my @values; while(<DATA>){   chomp;   push @values, /Name=(.+?)$/; }    print join " " => @values,"\n";  __DATA__ Name=Value1 Name=Value2 Name=Value3 
like image 33
aartist Avatar answered Sep 29 '22 20:09

aartist


The following will give all the matches to the regex in an array.

push (@matches,$&) while($string =~ /=(.+)$/g );
like image 44
champ e perl Avatar answered Sep 29 '22 20:09

champ e perl