ChinaUnix.net
 >> ChinaUnix.net > Perl

在 tr/// 中使用 regular expression?

作者:halihan     发表时间:2002/12/27 12:40pm

我想要在文件中的一些部分使用 tr/// 替换字符,例如:

Paul and his kids want to go to @peiking@ and live there.

换成

Paul and his kids want to go to @beijing@ and live there.

重点是只要替换在 @...@ 之内的字符,使用 tr/pkts/bjdx/
在 @...@ 之外的字符不做改变

请问要如何实行?谢谢!



此文章相关评论:
该文章有8个相关评论如下:(点这儿可以发表评论)
apile 发表于: 2002/12/27 01:09pm
#!/usr/bin/perl
$abc = 'Paul and his kids want to go to @peiking@ and live there.';

$abc=~/\@peiking\@/;

print $&."\n";
$abc=$`."\@beijing\@".$';
print $abc."\n";

you can't use tr to replace a string....
because in your case the whole char. int string will be replaced by the rule.
p---->b
k---->j
t---->d
s---->x

so you need to use var. of regular expression. $` && $'

 
apile 发表于: 2002/12/27 01:11pm
or another way...
$abc = 'Paul and his kids want to go to @peiking@ and live there.';
$abc=~s/\@peiking\@/\@beijing\@/g;
is  easier...
 
halihan 发表于: 2002/12/27 02:23pm
谢谢您的回复, 对不起我可能说得不清楚:
我的主要目标是使用此规则:
p->bk->jt->ds->x…
替换文件中所有在 @...@ 之内的字符
而规则共有数十条之多, 所以才想到使用 tr/pkts/bjdx/
但又不是替换整个文件, 而是只有在 @...@ 之内的字符
所以想不出解决方案…
当然使用 s///g 也可以, 但是数十条规则非常不好用,
请指点迷津,谢谢!

 
apile 发表于: 2002/12/27 10:02pm
you can use..
#!/usr/bin/perl
$abc = 'Paul and his kids want to go to @peiking@ and live there.';
$abc=~/\@peiking\@/;
$cde = $&;
$cde = tr/pkts/bjdx/;

$abc=$`.$cde.$';
print $abc."\n";

this is what you want...

 
apile 发表于: 2002/12/27 10:05pm
#!/usr/bin/perl
$abc = 'Paul and his kids want to go to @peiking@ and live there.';
$abc=~/\@(\w+)\@/;
$cde = $1;
$cde = tr/pkts/bjdx/;
$abc=$`.$cde.$';
print $abc."\n";

this is an example for general case.......
best regards....

 
halihan 发表于: 2003/01/02 10:08pm
啊! 真是太强了!! 非常感谢大侠专业的回复!!
小弟另有一问:
如果 $abc = 'Paul and his kids want to go to @peiking@ and live there……
不是只有一行, 而是整个文件, 而且一行中可能出现数个 @...@ 部分,
那么是否必须使用循环, 依序处理每一行才能办到?
还是有更高明的办法??
恳请指点迷津, 感激不尽!!
 
apile 发表于: 2003/01/03 08:18am
#!/usr/bin/perl

$abc = 'Paul and his kids want to go to @peiking@ and live there @peiking@';
$abc =~s/(\@\w+\@)/&fun1($1)/ge;
print $abc."\n";
sub fun1($){
 local($aa) = @_;
 $aa =~ tr/pkts/bjdx/;
 return $aa;
}

this is what you want.......

 
halihan 发表于: 2003/01/04 10:59pm
哇!!! 这就是我想要的!!! :em02:
大侠武功高强, 神乎其技, 行侠仗义, 在下万分佩服!!
请受在下一拜!!!  :em15:  
 
 

Copyright © ChinaUnix.net  *  转载请注明出处及作者