How I select a specific word in perl using regex?

Viewed 112

I've created a Shell script in Perl that should match the line with Girone : Girone Rosso and save just the Girone Rosso (that is a variable, so I was thinking to write it like [a-zA-Z]).

Here my attempt:

pdftotext -layout "$KMVAR_local_PathStr" - \
| perl -wne '
    if ( m!^Girone :\h+.+! ) {
        s!^Girone :\h+!!gm;
        print;
}
'
3 Answers

No need to match then match a second time using substitution.

perl -ne'print if s/^Girone\h*:\h*//'

But more general, you are asking how to capture. That's done using parens.

if ( /^Girone\h*:\h*(.*)/ ) {
   # ... do something with $1 ...
}

or

if ( my ($value) = /^Girone\h*:\h*(.*)/ ) {
   # ... do something with $value ...
}

You don't have to replace the part after the match, you can print the match making use of \K to clear the match buffer using ^Girone :\h+\K.+ where the part .+ will match 1+ characters.

^Girone :\h+\K.+

Regex demo

I am not very experienced with perl, but as an example:

my $str = "Girone : Girone Rosso";
if ($str =~ m/^Girone :\h+\K.+/) {
    print $&;
}

Output

Girone Rosso

I don't fully understand your question but if you just want to print out the name whenever it's encountered, you would do this. You can also use $. to print what line it matched on.


pdftotext -layout "$KMVAR_local_PathStr" - | perl -wne 'm/Girone : (Girone Rosso)/ and print "Line $.: $1\n"; '


See the Perl doc for more info.

Related