简体   繁体   中英

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.

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
$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

Try doing this :

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

just put like this,

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM