#!/usr/bin/perl use strict; use warnings; my @data = ( "dist: 45 km;", "dist: 45\nkm;", "dist:\n45 km;" ); foreach my $chunk( @data ){ my( $distance ) = $chunk =~ /dist:.*?(\d+).*?km;/s; print STDOUT "$distance\n"; } #### /dist: # match 'dist:' .*? # match anything (including newlines), but only until the next part of the pattern starts to match (\d+) # match 1 or more digits, and put these into $1 .*? # same as before km; # match 'km;' (not needed unless you want to match a number of these in one string) /s # treat the whole line as a single string