PExplorer
PExplorer

Reputation: 71

Extract delimited substrings from a string

I have a string that looks like this

my $source = "PayRate=[[sDate=05Jul2017,Rate=0.05,eDate=06Sep2017]],item1,item2,ReceiveRate=[[sDate=05Sep2017,Rate=0.06]],item3" ;

I want to use capture groups to extract only the PayRate values contained within the first [[...]] block.

$1 = "Date=05Jul2017,Rate=0.05,EDate=06Sep2017"

I tried this but it returns the entire string.

my $match =~ m/PayRate=\[\[(.*)\]\],/ ;

It is clear that I have to put specific patterns for the series of {(.*)=(.*)} blocks inside. Need expert advice.

Upvotes: 2

Views: 43

Answers (2)

shawnhcorey
shawnhcorey

Reputation: 3601

Use the /x modifier on match (and substitute) so you can use white space for easier reading and comments to tell what is going on. Limit the patterns by matching everything not in the pattern. [^\]]*? is better than .*?.

my ( $match ) = $line =~ m{
    Payrate \= \[\[  # select which part
    ( [^\]]*? )      # capture anything between square brackets
}x;

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

You are using a greedy match .*, which consumes as much input as possible while still matching, you're matching the first [[ to the last ]].

Instead, use a reluctant match .*?, which matches as little as possible while still matching:

my ( $match) = $source =~ /PayRate=\[\[(.*?)\]\]/;

Upvotes: 4

Related Questions