Home > Software engineering >  How I select a specific word in perl using regex?
How I select a specific word in perl using regex?

Time:11-05

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;
}
'

CodePudding user response:

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 ...
}

CodePudding user response:

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
  • Related