Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Match all occurrences?

Tags:

regex

perl

my @matches = ($result =~ m/INFO\n(.*?)\n/);

So in Perl I want to store all matches to that regular expression. I'm looking to store the value between INFO\n and \n each time it occurs.

But I'm only getting the last occurrence stored. Is my regex wrong?

like image 558
Takkun Avatar asked Jun 26 '12 13:06

Takkun


People also ask

What is the regular expression function to match all occurrences of a string?

Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() . Executes a search for a match in a string. It returns an array of information or null on a mismatch.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.

How do I check regex matches?

The match() regex method can also be used for checking the match which retrieves the result of matching a string against a regex: One of the differences between match() and test() methods is that the first works only with strings, the latter works also with integers.

What is the regular expression function to match all occurrences of a string in Python?

The search() function searches the string for a match, and returns a Match object if there is a match.


1 Answers

Use the /g modifier for global matching.

my @matches = ($result =~ m/INFO\n(.*?)\n/g);

Lazy quantification is unnecessary in this case as . doesn't match newlines. The following would give better performance:

my @matches = ($result =~ m/INFO\n(.*)\n/g);

/s can be used if you do want periods to match newlines. For more info about these modifiers, see perlre.

like image 104
Tim Avatar answered Sep 30 '22 12:09

Tim