Connecting Tech Pros Worldwide Help | Site Map

Regex question

Newbie
 
Join Date: Nov 2006
Posts: 4
#1: Nov 4 '06
I'm trying to match hostnames from a DNS zone file. Here's a sample line:

host.domain.com. A 192.168.0.1


How do I match just "host.domain.com"? That is, what regex would I use?

Thanks,
-KB
miller's Avatar
Moderator
 
Join Date: Oct 2006
Location: San Francisco, CA
Posts: 830
#2: Nov 5 '06

re: Regex question


You need to more explicitly state what you're trying to do. Are you trying to simply see if this "specific" hostname is within a line. Are you trying to extract the hostnames? And they are always the first item in the record? There are many different types of goals that would require a different regular expression, but since you didn't specify, I'll simply assume the easiest.

Expand|Select|Wrap|Line Numbers
  1. if ($line =~ m{\b\Qhost.domain.com\E\b}) {
  2.     print "specific host found";
  3. } else {
  4.     print "not found";
  5. }
  6.  
All that does is search for the literal string "host.domain.com" with word boundaries surrounding it. If you need help with anything more specific, you'll have to specify.
Newbie
 
Join Date: Nov 2006
Posts: 4
#3: Nov 5 '06

re: Regex question


Quote:

Originally Posted by miller

You need to more explicitly state what you're trying to do. Are you trying to simply see if this "specific" hostname is within a line. Are you trying to extract the hostnames? And they are always the first item in the record? There are many different types of goals that would require a different regular expression, but since you didn't specify, I'll simply assume the easiest.

Expand|Select|Wrap|Line Numbers
  1. if ($line =~ m{\b\Qhost.domain.com\E\b}) {
  2.     print "specific host found";
  3. } else {
  4.     print "not found";
  5. }
  6.  
All that does is search for the literal string "host.domain.com" with word boundaries surrounding it. If you need help with anything more specific, you'll have to specify.


Sorry, miller.

Yes, I will extract only the hostnames and they will be the 1st item in the record.

Okay, I saw that you used the word boundary -- I didn't think to use that. :)

Thanks!!
miller's Avatar
Moderator
 
Join Date: Oct 2006
Location: San Francisco, CA
Posts: 830
#4: Nov 5 '06

re: Regex question


If all you're trying to do is extract the first element from the line, then I suggest simplifying your logic:

Expand|Select|Wrap|Line Numbers
  1. if ($line =~ m{^(\S+)}) {
  2.     push @hostnames, $1;
  3. }
  4.  
The above simply pulls all characters until a space is reached. It is the simpliest logic that you could use, and will therefore catch all your hostnames.
Reply


Similar Perl bytes