Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Regex regular expression to split //

Tags:

regex

split

perl

I went through s'flow and other sites for simple solution with regex in perl.

$str = q(//////);#

Say I've six slash or seven, or other chars like q(aaaaa)

I want them to split like ['//','//'],

I tried @my_split = split ( /\/\/,$str); but it didn't work

Is it possible with regex?

Reason for this question is, say I have this domain name:

$site_name = q(http://www.yahoo.com/blah1/blah2.txt);

I wanted to split along single slash to get 'domain-name', I couldn't do it. I tried

split( '/'{1,1}, $sitename); #didn't work. I expected it split on one slash than two.

Thanks.

like image 273
Nalan P Avatar asked Mar 26 '26 15:03

Nalan P


1 Answers

The question is rather unclear.

To break a string into pairs of consecutive characters

my @pairs = $string =~ /(..)/g;

or to split a string by repeating slash

my @parts = split /\/\//, $string;

The separator pattern, in /.../, is an actual regex so we need to escape / inside it.

But then you say you want to parse URI?

Use a module, please. For example, there is URI

use warnings;
use strict;
use feature 'say';

use URI;

my $string = q(http://www.yahoo.com/blah1/blah2.txt);
my $uri = URI->new($string);

say "Scheme: ", $uri->scheme;
say "Path:   ", $uri->path;
say "Host:   ", $uri->host;
# there's more, see docs    

and then there's URI::Split

use URI::Split qw(uri_split uri_join);

my ($scheme, $auth, $path, $query, $frag) = uri_split($uri);

A number of other modules or frameworks, which you may already be using, nicely handle URIs.

like image 60
zdim Avatar answered Mar 29 '26 07:03

zdim