我正在尝试写一个正则表达式来修改电话号码。如果它是一个国际号码(非美国),我希望保留+符号(%2B后被URL编码)。如果它是一个国内号码,%2B应该被剥离,并更改为11位格式与一个1在前面。
这4个用例是:
%2B2125551000变成0112125551000(这应该被看作是一个国际数字,因为它以+[2-9]开头--用011代替+ )%2B12125551000变成12125551000 (因为这是+1,它是一个国内号码,去掉+)2125551000变成12125551000 (没有+的国内号码)12125551000变成12125551000 (没有+的国内号码)我一直试图在Linux上使用sed测试它:
进行匹配的表达式是:
((%2B)|)?((1)|)?([0-9]{10})然而,我不一定总是需要所有的5个论点。我只需要在字符串为%2B的情况下保留%2B[2-9]。
$ for line in %2B2125551000 %2B12125551000 12125551000 2125551000;do echo $line | sed -r 's/^((%2B|))?((1)|)?([0-9]{10})/one:\1 two:\2 three:\3 four:\4 five:\5/';done
one:%2B two:%2B three: four: five:2125551000
one:%2B two:%2B three:1 four:1 five:2125551000
one: two: three:1 four:1 five:2125551000
one: two: three: four: five:2125551000发布于 2012-09-24 21:07:14
好吧,让我看看,你想要什么:
s/^%2B(?=[2-9])/011/ || # this will do first rule and change %2B to 011
s/^%2B(?=1)// || # this will do second rule and strip off %2B
s/^(?:[2-9])/1$&/ ; # this will do third rule and add 1 to the beginning of the number
# Perl code
my @all = <DATA>;
for (@all){
s/^%2B(?=[2-9])/011/ or
s/^%2B(?=1)// or
s/^(?:[2-9])/1$&/ ;
print "line is $_ \n";
}
__DATA__
%2B2125551000
%2B1125551000
225551000
125551000https://stackoverflow.com/questions/12572525
复制相似问题