Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extract string in a line

Status
Not open for further replies.

winston6071

Programmer
Nov 22, 2000
52
AT
hello
i just start with perl regex, and it seems it takes another while to really get into it, i tried to manipulate the code examples in here for string manipulations, but ... anyway just to stupid :)

what i have:
50:\\hostname description 1. Floor

so i just want to get the hostname, so i know how to do it manually with pointers or some other technic but this powerful stuff of regex is maybe better for this
if someone gives an example, can you please comment it a little for understanding, i want to really get the thing, to know how to do different stuff

another thing
if you have this:
12:12:12:44:44:50
would you better use the split ? or anyhow else ?

many thanks in advance
 
post your data and expected output. This would help folks trying to help get a better grasp of what your wanting.
 
ok so shortly again
line to parse:
50:\\hostname description 1. Floor

expected output:
hostname
 
Code:
#!perl
use strict;
use warnings;

my $line = "50:\\hostname             description 1. Floor";
my ($hostname) = $line =~ /(\w+)\s/;
# or: my $hostname = $1 if $line =~ /(\w+)\s/;
print qq(\$hostname = "$hostname"\n);
 
many Thanks mike
your the best

works great in my code, i had this before
=~ / (\w+)/;
, see my failure now :)

thanks joe
 
Actually, I think /\\(\w+)\s/ is a little better. This tells Perl not to try to match until it sees a backslash. Without this, it will match the "50" at the beginning of the string, since digits are "word" characters, then give up and start over when it sees the colon. Still works, but /\\(\w+)\s/ is more efficient.

For an in-depth treatment of re's, I highly recommend Jeffrey Friedl's book "Mastering Regular Expressions." (Though I don't claim to u/s all of it, or always practice what it preaches. :))

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top