Search code examples
regexperl

Regex to Capture Specific 8-digit String in Variable using Perl


In my Perl script, I have a variable that contains a specific file path. I need to create a regular expression that can capture a specific 8-digit string from that variable.

When $file_path = "/home/attachments/00883227/sample.txt I want to capture the string of numbers immediately following "attachments".

My (unsuccessful) attempt:

if($file_path =~ /attachments\/(\d{1,2,3,4,5,6,7,8}+)/)
    { $number = $1; }

When I run this script, though, it looks like nothing is stored in the $number variable. The solution for this is probably very simple? Please pardon my ignorance, I am very new to Perl.


Solution

  • Close, just use (\d{8}), like:

    $file_path =~ /attachments\/(\d{8})\b/
    

    Also added \b so that it doesn't capture any longer numbers.