R Regex用于识别英国邮政编码

时间:2018-04-25 11:50:32

标签: r regex postal-code

我的问题类似于this,但我正在寻找具体的R内容。我有一个包含数万个地址的数据框,需要提取邮政编码。邮政编码在英国,格式为{LETTER_LETTER_DIGIT LETTER_LETTER_DIGIT}。类似于以下内容:

" 8,Longbow Close,\ r \ nHarlescott Lane,\ r \ nShrewsbury,\ r \ nEngland,\ r \ nSY1 3GZ"

我已使用此代码的变体与stringr无效:

str_extract('^(\\[Gg]\\[Ii]\\[Rr] 0\\[Aa]{2})|(((\\[A-Za-z]\\[0-9]{1,2})|((\\ 
[A-Za-z]\\[A-Ha-hJ-Yj-y]\\[0-9]{1,2})|((\\[AZa-z]\\[0-9]\\[A-Za-z])|(\\[A-Za- 
z]\\[A-Ha-hJ-Yj-y]\\[0-9]?\\[A-Za-z]))))\\[0-9]\\[A-Za-z]{2})$',alfa$Address) 

2 个答案:

答案 0 :(得分:2)

^$锚点要求模式匹配整个字符串。您可以使用\b(?:<pattern>)\b包装模式以匹配这些代码作为整个单词(\b是单词边界)。此外,角色类被破坏了#34;因为您转义了[起始括号(\[与文字[字符匹配)。另外,交换参数,第一个是输入,第二个是正则表达式。另外,要获得所有匹配,您需要使用str_extract_all而不是str_extract

你可以修改这样的代码:

library(stringr)
txt <- "8, Longbow Close,\r\nHarlescott Lane,\r\nShrewsbury,\r\nEngland,\r\nSY1 3GZ"
pattern <- "\\b(?:([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2}))\\b"
str_extract_all(txt, pattern)
# => [[1]]
#   [1] "SY1 3GZ"

答案 1 :(得分:0)

这是一种更易读的方式:

            if ($e{locate} =~ /\b([A-Z])([A-Z])([0-9])([A-Z]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6.$7;
                    $e{zips} = $1.$2.$3.$4.' ' .$5.$6.$7;
            } elsif ($e{locate} =~ /\b([A-Z])([0-9])([A-Z]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6;
                    $e{zips} = $1.$2.$3.' '.$4.$5.$6;
            } elsif ($e{locate} =~ /\b([A-Z])([0-9]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5;
                    $e{zips} = $1.$2.' '.$3.$4.$5;
            } elsif ($e{locate} =~ /\b([A-Z])([0-9])([0-9]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6;
                    $e{zips} = $1.$2.$3.' '.$4.$5.$6;
            } elsif ($e{locate} =~ /\b([A-Z])([A-Z])([0-9]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6;
                    $e{zips} = $1.$2.$3.' ' .$4.$5.$6;
            } elsif ($e{locate} =~ /\b([A-Z])([A-Z])([0-9])([0-9]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6.$7;
                    $e{zips} = $1.$2.$3.$4.' '.$5.$6.$7;
            }