[英]perl regex replace only part of string
I need to write a perl regex to convert 我需要编写一个Perl正则表达式进行转换
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
. 处理url时,最好使用
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: 我将尝试
/ge
路线:
$data =~ s{^|(\.)}{
( $1 && ',' ) . 'dc='
}ge;
e = evaluate replacement as Perl code. e =将替换评估为Perl代码。
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='
. 无论结果如何,都插入
'dc='
。
Note, that I like to use a brace style of delimiter on all my evaluated replacements. 请注意,我喜欢对所有评估的替换使用大括号样式的定界符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.