而不是編寫一個正則表達式,它可能更容易在多個步驟中完成。使用例子,你給:
x <- c('5%', '2.46%', '12.9%', '5 %', '2.46 %', '5 12.9 %',
'5 percent', '2.46 percent', '5 per cent',
'etc..', '<TD width="97%"></TD>')
get_pct <- function(x) {
x <- gsub('="[^"]+%"', '', x)
x <- gsub('\\s*per\\s*cent|\\s*%', '%', x)
is_pct <- grepl('\\d+(\\.\\d+)?', x)
as.numeric(ifelse(is_pct, gsub('.*?(\\d+\\.?\\d*)%.*', '\\1\\2', x), NA))
}
f(x)
[1] 5.00 2.46 12.90 5.00 2.46 12.90 5.00 2.46 5.00 NA NA
這裏的事情一步一步相同
# Eliminate percentages from html tags
x <- gsub('="[^"]+%"', '', x)
x
[1] "5%" "2.46%" "12.9%" "5 %" "2.46 %" "5 12.9 %"
[7] "5 percent" "2.46 percent" "5 per cent" "etc.." "<TD width></TD>"
# Standardize % symbol
x <- gsub('\\s*per\\s*cent|\\s*%', '%', x)
x
[1] "5%" "2.46%" "12.9%" "5%" "2.46%" "5 12.9%"
[7] "5%" "2.46%" "5%" "etc.." "<TD width></TD>"
# Find percentages
is_pct <- grepl('\\d+(\\.\\d+)?', x)
# Extract values
x <- ifelse(is_pct, gsub('.*?(\\d+\\.?\\d*)%.*', '\\1\\2', x), NA)
as.numeric(x)
[1] 5.00 2.46 12.90 5.00 2.46 12.90 5.00 2.46 5.00 NA NA
像' 「[0-9] + \\ [0 = 9] + *%。」 應該'工作。 「*」和「。」都是正則表達式中的特殊字符。見這裏:https://stackoverflow.com/questions/27721008/how-do-i-deal-with-special-characters-like-in-my-regex以及此網站:http://www.regular-expressions .info /瞭解更多信息。 – lmo
也許'grep(「[0-9] {1,2} \\。[0-9] {1,2}」,text)'? –
您最好使用xml解析函數提取相關屬性。這很容易。 –