user2007843
user2007843

Reputation: 609

Regex perl with letters and numbers

I need to extract a strings from a text file that contains both letters and numbers. The lines start like this

Report filename: ABCL00-67900010079415.rpt ______________________

All I need is the last 8 numbers so in this example that would be 10079415

while(<DATA>){
if (/Report filename/) {
  my ($bagID) = ( m/(\d{8}+)./ );
  print $bagID;
}

Right now this prints out the first 8 but I want the last 8.

Upvotes: 1

Views: 957

Answers (2)

Borodin
Borodin

Reputation: 126722

To match the last of anything, just precede it with a wildcard that will match as many characters as possible

my ($bag_id) = / .* (\d{8}) /x

Note that I have also use the /x modifier so that the regex can contain insignificant whitespace for readability. Also, your \d{8}+ is what is called a possessive quantifier; it is used for optimising some regex constructions and makes no difference at the end of the pattern

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You just need to escape the dot, so that it would match the 8 digit characters which exists before the dot charcater.

my ($bagID) = ( m/(\d{8}+)\./ );

. is a special character in regex which matches any character. In-order to match a literal dot, you must need to escape that.

Upvotes: 6

Related Questions