How to save consistent parts of a regular expression in Perl?

I want to sort all APIs in the following text file:

DLL Name: msvcrt.dll ... DLL Name: msvcrt.dll ... DLL Name: KERNEL32.dll ... DLL Name: WSOCK32.DLL 

I thought of something like

 $infostring = lc($infostring); while ($infostring =~ /dll name:/g) { print "found dll\n"; } 

The only problem is how to get the actual dll names or at least the position of the string found?

0
source share
2 answers

You need to expand your regex to write the name of the DLL:

 $infostring = lc($infostring); while ($infostring =~ /dll name: (\S+\.dll)/g) { print "found dll: $1\n"; } 

\S+\.dll will match one or more characters without spaces, followed by ".dll", and parentheses collect the text matched inside them and store it in the variable $1 . (If you had more than one set of parentheses, the second will go at $2 , the third at $3 , etc.)

Edit: It looks like the input specification was changed by editing the question when I wrote my answer ... The above information would be for a single input line containing all the DLL names. In the new format, with each of them on a separate line, you would like to use:

 while (my $infostring = <$input_filehandle>) { $infostring = lc($infostring); print "found dll: $1\n" if $infostring =~ /dll name: (\S+\.dll)/; } 

No need to mess around with /g in a regular expression or iterate over matches if there aren’t multiple matches on the same line.

+9
source
 while ($infostring =~ /DLL Name: (.*)/g) { print "found dll: $1\n"; } 

Read the perlre page. To capture a DLL name, you need to use a capture group (indicated by a bracket). You can then reference the captures later using $1 , $2 , ..., $n

+1
source

Source: https://habr.com/ru/post/1305693/


All Articles