469,281 Members | 2,484 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,281 developers. It's quick & easy.

Extract a substring between two elements

2
Hello there

I'm new with Perl... I need to extract a substring between two elements.
I'm working with urls and I need to get the text between "http://" and the first "/" in that string.

For example, in the following string:
Expand|Select|Wrap|Line Numbers
  1. http://www.example.com/test/index.html
I want to retrieve
Expand|Select|Wrap|Line Numbers
  1. www.example.com
How can I do that? Thanks!!!
Nov 12 '08 #1
6 15875
nithinpes
410 Expert 256MB
What did you try? Post the regex that you tried.
Nov 12 '08 #2
tcouto
2
I'm currently removing the "http://" with the substring function, since it's a constant number of characters
Expand|Select|Wrap|Line Numbers
  1. sub get_blogname{ 
  2. my ($blogurl) = @_;
  3. my $blogname = substr($blogurl, 7);
  4.  
  5. return $blogname;
  6. }
I just don't know how to retrieve all the characters in the $blogname until the first "/" appears
Nov 12 '08 #3
KevinADC
4,059 Expert 2GB
one possibility:

Expand|Select|Wrap|Line Numbers
  1. sub get_blogname{ 
  2.    my ($blogurl) = @_;
  3.    my ($blogname) = $blogurl =~ m|^(?:http://)?([^/]+)|i;
  4.    return $blogname;
  5. }
Nov 12 '08 #4
Ganon11
3,652 Expert 2GB
Or possibly:

Expand|Select|Wrap|Line Numbers
  1. my $url =~ m#//(.*?)/#;
  2. my $blog_url = $1;
Nov 12 '08 #5
eWish
971 Expert 512MB
Unless the data you are interested in is fixed length then substr is not the way to go. I would suggest that you use one of the other suggestions. However, if it is a fixed length the substr would be fine.

Expand|Select|Wrap|Line Numbers
  1. my $url = 'http://www.somedomain.com/somepage.html';
  2. print substr($url,7,18);

Or in a subroutine.
Expand|Select|Wrap|Line Numbers
  1. print &get_url('http://www.somedomain.com/somepage.html');
  2.  
  3. sub get_url {
  4.     croak "You did not pass the proper number of arguments\n" if @_ != 1;
  5.     return substr($_[0],7,18);
  6. }
--Kevin
Nov 13 '08 #6
We can do this way also

Expand|Select|Wrap|Line Numbers
  1. $text = "http://www.example.com/test/index.html";
  2.  
  3. $text =~s/http:\/\///i;
  4.  
  5. $split1 = (split /\//,$text)[0];
  6. print $split1;
Check this out
Nov 14 '08 #7

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Tim Smith | last post: by
4 posts views Thread by rdraider | last post: by
9 posts views Thread by Sharon | last post: by
1 post views Thread by Nick | last post: by
1 post views Thread by Patrick Sullivan | last post: by
7 posts views Thread by Sling | last post: by
5 posts views Thread by =?Utf-8?B?aWxy?= | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.