Regex - Match all occurrences?

29,276

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.

Share:
29,276
Takkun
Author by

Takkun

Updated on July 09, 2022

Comments

  • Takkun
    Takkun 4 months
    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?

  • Ωmega
    Ωmega over 10 years
    Why /s is needed? I see no reason for that, as his match should not contain any new-line character(s).
  • Tim
    Tim over 10 years
    You're right that it doesn't matter in this case, but since he didn't knew about /g and was matching multi-line strings, it seemed reasonable that he would need /s sooner or later.
  • Tim
    Tim over 10 years
    m/INFO\n(.*)\n/g would be quicker but also less similar to OP's original try.
  • Ωmega
    Ωmega over 10 years
    You should update your answer with this one :) You can still add some notes to your answer to give OP a lessons about /g and /s, sure...