Cristian
Cristian

Reputation: 7145

Perl Compare Strings without Numbers

I have 2 variables:

my $var1 = 'package-name-1.4';
my $var2 = 'package-name-1.5';

What I'm trying to do, is to compare $var1 to $var2, while excluding the numbers.

I have looked online and tried Regex but I can't get it working, I'd greatly appreciate some help.

What I have in mind is as follows:

if (removeNumbers($var1) =~ removeNumbers($var2))

So that the result would be like comparing: package-name- with package-name-, thus evaluating true.

Thanks in advance for your help!

Upvotes: 1

Views: 204

Answers (3)

raina77ow
raina77ow

Reputation: 106385

Well, the easiest approach is just to remove all digits altogether:

sub remove_numbers {
  my ($orig) = @_;
  $orig =~ s/\d+//g;
  return $orig;
}

But it's a bit naïve: for example, some-package-1.4.1 and some-package-1.4 would be not equal. It's better to remove dots as well, but only if they follow digits (serving as separators).

  $orig =~ s/\d+[.]?//g;

Even more, perhaps the first hyphen that precedes the number should go also (so 'package-name' and 'package-name-1' (and even 'package-name-1.0-some-fancy-line' and 'package-name-some-fancy-line') would be treated the same:

  $orig =~ s/-?\d+[.]?//g;  

UPDATE: Yet there's more than one way to do it:

  $orig = substr $orig, 0, rindex $orig, '-';

It's applicable if all the strings have the same format (version numbers are always at the end of the string, always follow the last hyphen, which is always there):

Used as follows:

if (remove_numbers($var1) eq remove_numbers($var2))

Upvotes: 4

Borodin
Borodin

Reputation: 126722

In this instance it is probably best simply to extract all the "words" (here meaning alphabetic strings) and compare the strings containing just those

For instance

sub words_only {
  join ' ', shift =~ /\b[a-z]+\b/ig;
}

would turn both package-name-1.4 and package-name-1.5 into package name, so this script correctly prints MATCH

use strict;
use warnings;

my $var1 = 'package-name-1.4';
my $var2 = 'package-name-1.5';

print words_only($var1) eq words_only($var2) ? 'MATCH' : 'NO MATCH';

sub words_only {
  join ' ', shift =~ /\b[a-z]+\b/ig;
}

Upvotes: 3

urbanspr1nter
urbanspr1nter

Reputation: 1357

If your variables contain the same formatting, then you can try removing the digits in the strings and compare the results.

Upvotes: 0

Related Questions