LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Trying to combine lookahead and variable substitution (http://www.linuxquestions.org/questions/programming-9/trying-to-combine-lookahead-and-variable-substitution-667374/)

djeepp 09-03-2008 03:46 PM

Trying to combine lookahead and variable substitution
 
I've tried this in a few different tools, but I think perl is what I want to use. I'm not too familiar with it so be gentle.

I'm trying to strip off characters from a single line of text. I want to end up with only the version of a package name from this:

"recommended : bzip2-program-1.0.3"

So I figured I would do a non-greedy search for a dash, then one or more digits since it could very well be:

"recommended : bzip2-program-10.0.3"

Then, look ahead to find the period, then use a place holder to hold the version up to another dash in case I have something like this:

"recommended : bzip2-program-1.0.3-12"

I want to end up with: "1.0.3"

Any suggestions would be much appreciated. If you have a suggestion to use another tool, I would love to hear it as well.

keefaz 09-03-2008 04:32 PM

You could use a regular expression with perl
Code:

s/^.+-(\d+\.?\d+\.?\d+)-?\d*/\1/;
I see this as:
^.+- : match one or more caracter until the dash (included)
(\d+\.?\d+\.?\d+): match one digit or more followed by a dot or not, etc...
-? : match one dash or not
\d* : match zero or more digit

[edit]
Note that it will remove the "-12" from "1.0.3-12", it is what you want if I understand correctly, no?

You use it like:
Code:

my $str;
$str = "recommended : bzip2-program-1.0.3-12";
$str =~ s/^.+-(\d+\.?\d+\.?\d+)-?\d*/\1/;
print $str . "\n";

$str = "recommended : bzip2-program-1.0.3";
$str =~ s/^.+-(\d+\.?\d+\.?\d+)-?\d*/\1/;
print $str . "\n";



All times are GMT -5. The time now is 04:42 PM.