facebook has asked for the wisdom of the Perl Monks concerning the following question:

Hi all. I have a string that exists of words. Some of these words have numbers in them. those are the words i am looking for. This is what i came up with:

$names = "1Petrus2 Joh4an Smit 2johnny99 Julius 789"; while($names =~ /\b(\w*\d+\w*)\b/g){ print "$1\n"; }

this looks to be working. Can you tell me if this is the correct way or are there better ways?

Replies are listed 'Best First'.
Re: words with numbers in them
by Corion (Patriarch) on Jul 31, 2018 at 14:17 UTC

    Is "789" a word?

    Also, \w will already match digits, while "Motörhead666" might be considered a word, but will not be matched by your regular expression.

    Maybe have a look at perlre and the character classes to choose the ones that are closer to your definition of "word".

Re: words with numbers in them
by Paladin (Vicar) on Jul 31, 2018 at 18:52 UTC
    If your definition of "word" in this case, is non-whitespace characters separated by whitespace, then I'd split on white space, then grep the resulting array for elements containing numbers.
    my $names = "1Petrus2 Joh4an Smit 2johnny99 Julius 789"; my @words = split /\s+/, $names; my @numwords = grep /\d/, @words;

      You are wright, silly me. Thank you.

        No need to split and grep, just simplify your regex :)

        #!/usr/bin/perl use strict; use warnings; my $names = '1Petrus2 Joh4an Smit 2johnny99 Julius 789 one 2two three3 fo44ur ..5.. six seven, seven7, eight--8--nine '; while( $names =~ /(\S*\d\S*)/g ) { print "$1\n"; }
Re: words with numbers in them
by BillKSmith (Monsignor) on Jul 31, 2018 at 14:50 UTC
    Looks good to me. It seems a bit strange depending on \w to match all but one of the digits in names that contain more than one, but it works!
    Bill