tim
tim

Reputation: 45

How to match a number but not a string and number together?

I have a variable like this

p <= 0;
p <= q0;

I want to get only the line p <= q0 but not p <= 0 so I used the code below to get the the thing except number but it cannot get the q0 also since behind q there is a number.

if ($string2 =~ m/^(.*)(<=)(.*)(;)/g) {
     unless ($3 =~ /[0-9]/) {
        push @des, $1;
        push @source, $3;
     }
}

This is part of the code to match these two lines. $string 2 is first p<=0 and follow by p<=q0.

Upvotes: 1

Views: 71

Answers (3)

TimK
TimK

Reputation: 4835

You might be able to do it with just one match, depending on exactly what you want. If you want to match where the right-hand side is an identifier starting with a letter, this would work:

if ($string2 =~ m/^(.*)<=\s*([a-z]\w*)\s*;/gi) {
    push @des, $1;
    push @source, $2;
}

Upvotes: 0

elcaro
elcaro

Reputation: 2297

Easiest way with regex would be to check if $3 does NOT match any letters....

if ( $3 !~ /[A-z]/) { ... }

If you just want to check if $3 looks like a number, then use looks_like_number... It's in the core.

use Scalar::Util 'looks_like_number';

# Later...

if ( $string2 =~ m/^(.*)(<=)(.*)(;)/g ) {
    if ( looks_like_number($3) ) {
        push @des, $1;
        push @source, $3;
    }
}

EDIT

Forgot to point out that once you do another regex match, you lose the temporary capture variables (eg, $1, $2, etc).

Use named captures to get around this. Also, I suspect that you do not need to capture the <= and the ;. If that is the case, then you do not need to wrap them in brackets.

if ( $string2 =~ m/^(?<des>.*) <= (?<source>.*);/ ) {
    if ( $+{source} !~ /[A-z]/) {
        push @des, $+{des};
        push @source, $+{source};
    }
}

Upvotes: 1

cur4so
cur4so

Reputation: 1820

if($string2=~m/^([a-z,0-9]+)\s*(<=)\s*([a-z,0-9]+)(;)/g){
     my $d=$1;   
     my $s=$3;
     if ($3 =~ /[a-z]/){  
        push @des, $d;
        push @source, $s;
     }
}

Upvotes: 0

Related Questions