quick Regular Expression question

The Dancing Peacock

Diamond Member
Dec 22, 1999
3,385
0
0
I have a variable in Perl that is set as seen below. I want to extract <name> and make that the new value of $host. I know that I can use split to split on the . and then do it, but I want to do it with a regex without doing an "if" statement. Someone at work told me there should be a way to do it.

The machine name is "lid" followed by 2 - 4 digits, but I used 0,5 in case of future machine naming.

$host = <name>.<domain>.<ext>

I tried to do this $host =~ s/(lid\d{0,5})/$1/g

but it doesn't change the name its still has lidXXXX.<domain>.<ext>

any ideas?


Thanks.
 

gentobu

Golden Member
Jul 6, 2001
1,546
0
0
$host =~ s/(lid\d{0,5})/$1/g

I think that your (lid\d{0,5}) is being captured into the $1 variable so it prints out the lidxxx.<domain>.<ext>.
So I think you could try something like (lid)(\d{0,5}) the first (lid) should capture the text "lid" and put it into $1 and the second should capture the xxxx part of the machines name into $2.
Anyway I tried this:

open (names, "test.txt");
while (<names> ){
print if s/(lid)(\d{0,5})/$2/g;

}

on this test file:

lid1234.<domain>.<ext>
lid1454.<domain>.<ext>
lid8734.<domain>.<ext>
lid1894.<domain>.<ext>

and got this:

1234.<domain>.<ext>
1454.<domain>.<ext>
8734.<domain>.<ext>
1894.<domain>.<ext>

Edit: ok I somehow came to the conclusion that you wanted to remove the "lid" part from the <name>...oh well now you have the regex to do it
:)
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
If you want to keep the "lid":
$host =~ s/^(lid.*?)\..*$/$1/;

otherwise:
$host =~ s/^lid(.*?)\..*$/$1/;