0

我正在尝试编写一个正则表达式来修改电话号码。如果它是国际号码(非美国),我希望+保留该符号(%2B在 URL 编码之后)。如果是国内号码,%2B应该去掉,改成1前面加a的11位格式。

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
4

1 回答 1

0

好的,让我们看看,你想要什么:

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
125551000
于 2012-09-24T21:07:14.587 回答