带替换和选项的正则表达式

时间:2012-09-24 20:36:28

标签: regex

我正在尝试编写正则表达式来修改电话号码。如果是国际号码(非美国),我希望保留+符号(经过URL编码后%2B)。如果是国内号码,则应删除%2B,并在前面使用1更改为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

1 个答案:

答案 0 :(得分: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
相关问题