1

テキストからの抽出に取り組んでいます'stringr'-RIでパッケージを使用すると、次の例が見つかりました:

strings <- c(" 219 733 8965", "329-293-8753 ", "banana", "595 794 7569",
"387 287 6718", "apple", "233.398.9187 ", "482 952 3315",
"239 923 8115", "842 566 4692", "Work: 579-499-7527", "$1000",
"Home: 543.355.3679")
pattern <- "([2-9][0-9]{2})[- .]([0-9]{3})[- .]([0-9]{4})"
str_extract(strings, pattern)
str_extract_all(strings, pattern)

ただし、私の文字列は次の形式です。

strings <- c("87225324","65-62983211","65-6298-3211","8722 5324","(65) 6296-2995","(65) 6660 8060","(65) 64368308","+65 9022 7744","+65 6296-2995","+65-6427 8436","+65 6357 3323/322")

しかしpattern、上記のすべての形式を抽出する方法についてはわかりません。

4

2 に答える 2

4

以下のコードは、質問のケースをカバーしています。データ内に他の文字の組み合わせが見つかった場合は、それを一般化できることを願っています。

# Phone numbers (I've added an additional number with the "/" character)
strings <- c("87225324","65-62983211","65-6298-3211","8722 5324",
           "(65) 6296-2995","(65) 6660 8060","(65) 64368308","+65 9022 7744",
           "+65 6296-2995","+65-6427 8436","+65 6357 3323/322", "+65 4382 6922/6921")

# Remove all non-numeric characters except "/" (your string doesn't include any
# text like "Work:" or "Home:", but I included a regex to deal with those cases
# as well)
strings.cleaned = gsub("[- .)(+]|[a-zA-Z]*:?","", strings)

# If you're sure there are no other non-numeric characters you need to deal with 
# separately, then you can also do the following instead of the code above: 
# gsub("[^0-9/]","", strings). This regex matches any character that's not 
# a digit or "/".

strings.cleaned
 [1] "87225324"       "6562983211"     "6562983211"     "87225324"       "6562962995"    
 [6] "6566608060"     "6564368308"     "6590227744"     "6562962995"     "6564278436"    
[11] "6563573323/322" "6543826922/6921"

# Separate string vector into the cleaned strings and the two "special cases" that we 
# need to deal with separately
special.cases = strings.cleaned[grep("/", strings.cleaned)]
strings.cleaned = strings.cleaned[-grep("/", strings.cleaned)]

# Split each phone number with a "/" into two phone numbers
special.cases = unlist(lapply(strsplit(special.cases, "/"), 
                          function(x) {
                            c(x[1], 
                            paste0(substr(x[1], 1, nchar(x[1]) - nchar(x[2])), x[2]))
                          }))
special.cases
[1] "6563573323" "6563573322" "6543826922" "6543826921"

# Put the special.cases back with strings.cleaned
strings.cleaned = c(strings.cleaned, special.cases)

# Select last 8 digits from each phone number
phone.nums = as.numeric(substr(strings.cleaned, nchar(strings.cleaned) - 7, 
                                                nchar(strings.cleaned)))
phone.nums
 [1] 87225324 62983211 62983211 87225324 62962995 66608060 64368308 90227744 62962995 64278436
[11] 63573323 63573322 43826922 43826921
于 2014-05-06T17:22:34.960 に答える