Reputation: 35
I'm new to perl, I have come across a scenario where I have to extract D[number]
from a word.
example :
If input string is D11C1
, D11
should be extracted
If input string is D1C12
, D1
should be extracted.
Upvotes: 0
Views: 69
Reputation: 2695
my ($d) = $input =~ m/(D\d+)/;
Test:
perl -E 'while(my $input = shift) { my ($d) = $input =~ m/(D\d+)/; say $d }' D11C1 D1C1
D11
D1
Upvotes: 1
Reputation: 56
You may use something like:
$word =~ /.*(D\d+).*/;
my $res = $1;
\d+ - matches at least one digit.
Upvotes: 0
Reputation: 241768
Use a regular expression.
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
for my $string (qw( D11C1 D1C12 )) {
my ($extracted) = $string =~ /D[0-9]+/g;
say $extracted;
}
D
matches itslef, [0-9]
matches digits, +
means the digit can be repeated one or more times. The /g
at the end, in this case, just makes the expression return the matching part of the string. See perlre for details.
Upvotes: 1