Reputation: 47
I'm trying to match a string that contains alphanumeric, digits and dot.
Some examples of what I'm trying to match:
my @patternsTomatch = (
'SAN100.25.36.2', # Valid string
, 'DF1.2.3.5', # Valid string
, 'BADPATTERN', # In-Valid string
, '12BADPATTERN', # In-Valid string
, '.DF1.2.3.5', # In-Valid string
, 'SAN100.25.36.2.' # In-Valid string
);
foreach my $pattern (@patternsTomatch) {
if ( $pattern =~ /^([a-z|A-Z]+)(\d+\.)(.*)$/ ) { print " $pattern \n"; }
}
But above attempt is not working correctly?
Also, need a regular expression to match the fixed format string XC1.2.3.4_25 in seprate condition.
Thanks.
Upvotes: 2
Views: 1152
Reputation: 6808
Made code as simple as possible
use strict;
use warnings;
use feature 'say';
my @match = grep { chomp; /^[a-z]+\d+(:?\.\d+)+(:?_\d+)?$/i } <DATA>;
map{ say } @match;
__DATA__
SAN100.25.36.2
DF1.2.3.5
BADPATTERN
12BADPATTERN
.DF1.2.3.5
SAN100.25.36.2.
XC1.2.3.4_25
output
SAN100.25.36.2
DF1.2.3.5
XC1.2.3.4_25
Upvotes: 0
Reputation: 132896
I think you want something more like this:
my @candidates = (
'SAN100.25.36.2', # Valid string
'DF1.2.3.5', # Valid string
'BADPATTERN', # In-Valid string
'12BADPATTERN', # In-Valid string
'.DF1.2.3.5', # In-Valid string
'SAN100.25.36.2.' # In-Valid string
);
# store the pattern in a variable to get it out of the way
# of the logic
my $pattern = qr/
\A # beginning of string
[a-z]+ # latin letters, case insensitive
\d+ # digits
(?: # groups of . and digits
\.
\d+
)+
(?: # optional _ digits at end (or leave this group out)
_
\d+
)?
\z # end of string
/ix; # /i - case insenstive /x - expanded format
foreach my $candidate ( @candidates ) {
if( $candidate =~ $pattern ) {
print "$candidate matched\n";
}
else {
print "$candidate missed\n";
}
}
Upvotes: 2
Reputation: 163477
You might first match 1+ chars [A-Za-z]+
(Note that you don't need the pipe in the character class) and then repeat matching digits with a dot in between:
^[A-Za-z]+\d+(?:\.\d+)+$
To match an underscore and digits at the end, you could add matching an underscore and 1+ digits at the end of the pattern before asserting the end of the string:
^[A-Za-z]+\d+(?:\.\d+)+_\d+$
Upvotes: 3