Ras
Ras

Reputation: 547

How to verify if a variable value contains a character and ends with a number using Perl

I am trying to check if a variable contains a character "C" and ends with a number, in minor version. I have :

my $str1 = "1.0.99.10C9";
my $str2 = "1.0.99.10C10";
my $str3 = "1.0.999.101C9";
my $str4 = "1.0.995.511";
my $str5 = "1.0.995.AC";

I would like to put a regex to print some message if the variable has C in 4th place and ends with number. so, for str1,str2,str3 -> it should print "matches". I am trying below regexes, but none of them working, can you help correcting it.

my $str1 = "1.0.99.10C9";

if ( $str1 =~ /\D+\d+$/ ) {
   print "Candy match1\n";
}
if ( $str1 =~ /\D+C\d+$/ ) {
   print "Candy match2\n";
}

if ($str1 =~ /\D+"C"+\d+$/) {
print "candy match3";
}

if ($str1 =~ /\D+[Cc]+\d+$/) {
print "candy match4";
}

if ($str1 =~ /\D+\\C\d+$/) {
print "candy match5";
}

Upvotes: 1

Views: 497

Answers (3)

Polar Bear
Polar Bear

Reputation: 6798

Lets look what regex should look like:

start{digit}.{digit}.{2-3 digits}.{2-3 digits}C{1-2 digits}end

  • very very strict qr/^1\.0\.9{2,3}\.101?C\d+\z/ - must start with 1.0.99[9]?.
  • very strict qr/^1\.\0.\d{2,3}\.\d{2,3}C\d{1,2}\z/ - must start with 1.0.
  • strict qr/^\d\.\d\.\d{2,3}\.\d{2,3}C\d{1,2}\z/
  • relaxed qr/^\d\.\d\.\d+\.\d+C\d+\z/
  • very relaxed qr/\.\d+C\d+\z/
use strict;
use warnings;
use feature 'say';

my @data = qw/1.0.99.10C9 1.0.99.10C10 1.0.999.101C9 1.0.995.511 1.0.995.AC/;
#my $re   = qr/^\d\.\d\.\d+\.\d+C\d+\z/;
my $re   = qr/^\d\.\d\.\d{2,3}\.\d{2,3}C\d+\z/;

say '--- Input Data ---';
say for @data;

say '--- Matching -----';
for( @data ) {
    say 'match ' . $_ if /$re/;
}

Output

--- Input Data ---
1.0.99.10C9
1.0.99.10C10
1.0.999.101C9
1.0.995.511
1.0.995.AC
--- Matching -----
match 1.0.99.10C9
match 1.0.99.10C10
match 1.0.999.101C9

Upvotes: -1

Barmar
Barmar

Reputation: 781058

if ($str1 =~ /C[^.]*\d$/)
  • C matches the letter C.
  • [^.]* matches any number of characters that aren't .. This ensures that the match won't go across multiple fields of the version number, it will only match the last field.
  • \d matches a digit.
  • $ matches the end of the string. So the digit has to be at the end.

Upvotes: 4

Zylvian
Zylvian

Reputation: 82

I found it really helpful to use https://www.regextester.com/109925 to test and analyse my regex strings.

Let me know if this regex works for you:

((.*\.){3}(.*C\d{1}))

Following your format, this regex assums 3 . with characters between, and then after the third . it checks if the rest of the string contains a C.

EDIT:

If you want to make sure the string ends in a digit, and don't want to use it to check longer strings containing the formula, use:

^((.*\.){3}(.*C\d{1}))$

Upvotes: -1

Related Questions