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

Hello Monks, I have some strings example:
"1-2, 3-4, 5-6" or "1-2, 3-4" or "1-2"
I want to capture the last character in these strings. The last character will always be a digit. But this string may have any number of patterns like "1-2" or "3-4". Can anyone please suggest some rex for it. Thanks!

Replies are listed 'Best First'.
Re: String matching problem
by merlyn (Sage) on May 08, 2007 at 10:43 UTC
    This captures the last character, also asserting it is a digit.
    my ($last_char_digit) = ($string =~ /(\d)\z/);
    If your "always" isn't true, then the value will be undef.
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: String matching problem
by RL (Monk) on May 08, 2007 at 10:58 UTC

    my $string = "1-2, 3-4, 5-6"; #strip anything but the last digit, $string =~ s/^.*(\d)$/$1/; # string now holds only the last digit, rest should be removed

    or

    my $last_digit = ''; if ($string =~ /(\d)$/) { $last_digit = $1; }

    or

    my $last_digit = ''; if ($string =~ /(\d){1}$/) { $last_digit = $1; }

    In the last example you may replace {1} if you want any other number of digits from the end of the string

    Hope this helps
    RL

Re: String matching problem
by cool (Scribe) on May 08, 2007 at 11:29 UTC
    I hope you mean the very last digit of a line, not the last digit of '-' pattern.
    #! /usr/bin/perl use warnings ; use strict; open(FH,"infile") or die "File cant be opened\n"; while (<FH>) { if (m/\d-(\d)"$/) { print "$1\n"; } }
    Infile
    "1-2, 3-4, 5-6" or "1%5, 3-4" or "1-2" A6 12
Re: String matching problem
by syphilis (Archbishop) on May 08, 2007 at 13:33 UTC
    Admittedly it doesn't answer the question that was asked, but it may be worth pointing out that substr($string, -1) will return the last character in $string.

    Cheers,
    Rob
      substr($string, -1) will return the last character in $string.
      As does chop $string. I think that's the first time I've used chop.

      Actually its second last character not the last one... so I think

      substr($string, -2, 1)

      would be more appropriate

        Actually its the last character. I used double codes to just suggest that its a string. Thanks everyone for the help!