Search code examples
regexperlnon-greedy

Ungreedy regexp in Perl


I'm trying to capture a string that is like this:

document.all._NameOfTag_ != null ;

How can I capture the substring:

document.all._NameOfTag_

and the tag name:

_NameOfTag_

My attempt so far:

if($_line_ =~ m/document\.all\.(.*?).*/)
{

}

but it's always greedy and captures _NameOfTag_ != null


Solution

  • The lazy (.*?) will always match nothing, because the following greedy .* will always match everything.

    You need to be more specific:

    if($_line_ =~ m/document\.all\.(\w+)/)
    

    will only match alphanumeric characters after document.all.