Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need Perl regex which matches every a software version starting from 3.10.1.0 and all further versions numbering

This is my test case.

A cmd_1, which was working until version 3.10.0.0, will not work in future versions. Cmd_2 is introduced in 3.10.1.0 and will be the valid replacement going forward.

I need to add a condition for the above scenario. For older versions before 3.10.1.0, cmd_1 has to execute, and for 3.10.1.0 and beyond, cmd_2 has to execute.

I tried as below:

if ( ( $version =~ /^3\.10\.[1-9]/ ) || ( $version =~ /^3\.[1-9][0-9]/ ) || ( $version =~ /^[4-9]/ ) {
    # execute cmd_2;
}else{
    # execute cmd_1;
} 

The above regex fails in a few cases. For example, in the case of version= 3.10.0.0, cmd_2 will be executed, which is invalid.

Cmd_2 has to execute in versions like:

3.10.1.0, 3.10.2.0, 3.11.0.0, 3.11.2.0, 3.20.0.0, 4.0.0.0, 5.0.0.0, 10.0.0.0

Cmd_1 has to execute in versions like:

3.10.0.0, 3.9.0.0, 3.1.0.0, 3.0.0.0, 2.0.0.0, 1.0.0.0

I tried a few more regexes but was not able to find a perfect one. Please help me with this.

Thanks in advance.

like image 569
Subhash Avatar asked Aug 12 '19 12:08

Subhash


People also ask

What is the meaning of $1 in Perl regex?

$1 equals the text " brown ".

How do I match a number in Perl?

The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its equivalent to [0-9]. In the regex /\d/ will match a single digit. The \d is standardized to “digit”.


2 Answers

Don't use a regex pattern for this.

use version qw( );

if ($version >= version->declare("3.10.1.0")) {
   ...
} else {
   ...
}
like image 189
ikegami Avatar answered Nov 15 '22 06:11

ikegami


This regex should do what you want.

^(?:[4-9]|[1-9]\d+)(?:\.\d+){3}|3\.[2-9]\d(?:\.\d+){2}|3\.1[1-9](?:\.\d+){2}|3\.10\.[1-9]\d?\.\d+$

It looks for all the cases where cmd_2 should run i.e.

[1-9]x.x.x.x
[4-9].x.x.x
3.[2-9]x.x.x
3.1[1-9].x.x
3.10.[1-9]x.x
3.10.[1-9].x

Demo on regex101

like image 29
Nick Avatar answered Nov 15 '22 08:11

Nick