Bharath K
Bharath K

Reputation: 2119

perl regex replace only part of string

I need to write a perl regex to convert

site.company.com => dc=site,dc=company,dc=com

Unfortunately I am not able to remove the trailing "," using the regex I came with below. I could of course remove the trailing "," in the next statement but would prefer that to be handled as a part of the regex.

$data="site.company.com";
$data =~ s/([^.]+)\.?/dc=$1,/g;
print $data;

This above code prints:

dc=site,dc=company,dc=com,

Thanks in advance.

Upvotes: 1

Views: 1490

Answers (5)

Axeman
Axeman

Reputation: 29854

I'm going to try the /ge route:

$data =~ s{^|(\.)}{
    ( $1 && ',' ) . 'dc='
}ge;

e = evaluate replacement as Perl code.

So, it says given the start of the string, or a dot, make the following replacement. If it captured a period, then emit a ','. Regardless of this result, insert 'dc='.

Note, that I like to use a brace style of delimiter on all my evaluated replacements.

Upvotes: 0

vedagiri
vedagiri

Reputation: 21

just put like this,

$data="site.company.com";
$data =~ s/,dc=$1/dc=$1/g; #(or) $data =~ s/,dc/dc/g;
print $data;

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 185720

Try doing this :

my $x = "site.company.com";
my @a = split /\./, $x;
map { s/^/dc=/; } @a;
print join",", @a;

Upvotes: 1

TLP
TLP

Reputation: 67910

When handling urls it may be a good idea to use a module such as URI. However, I do not think it applies in this case.

This task is most easily solved with a split and join, I think:

my $url = "site.company.com";
my $string = join ",",            # join the parts with comma
             map "dc=$_",         # add the dc= to each part
             split /\./, $url;    # split into parts

Upvotes: 4

Vijay
Vijay

Reputation: 67291

$data =~s/\./,dc=/g&&s/^/dc=/g;

tested below:

> echo "site.company.com" | perl -pe 's/\./,dc=/g&&s/^/dc=/g'
dc=site,dc=company,dc=com

Upvotes: 2

Related Questions