在Linux上的R中的字符串中删除(非破坏)空格字符

时间:2017-05-02 09:19:41

标签: html r regex linux string

This question似乎可以轻松删除R中字符串中的空格字符。但是,当我加载下表时,我无法删除两个数字之间的空格(例如。11 846.4 ):

require(XML)
library(RCurl)
link2fetch = 'https://www.destatis.de/DE/ZahlenFakten/Wirtschaftsbereiche/LandForstwirtschaftFischerei/FeldfruechteGruenland/Tabellen/AckerlandHauptfruchtgruppenFruchtarten.html'

theurl = getURL(link2fetch, .opts = list(ssl.verifypeer = FALSE) ) # important!
area_cult10 = readHTMLTable(theurl, stringsAsFactors = FALSE)
area_cult10 = data.table::rbindlist(area_cult10)

test = sub(',', '.', area_cult10$V5) # change , to . 
test = gsub('(.+)\\s([A-Z]{1})*', '\\1', test) # remove LETTERS
gsub('\\s', '', test) # remove white space?

为什么我无法删除test[1]中的空格? 谢谢你的建议!这可能不是空间角色吗?也许答案很简单,我忽视了一些事情。

1 个答案:

答案 0 :(得分:4)

您可以将test创建简化为仅2步并仅使用1 PCRE 正则表达式(请注意perl=TRUE参数):

test = sub(",", ".", gsub("(*UCP)[\\s\\p{L}]+|\\W+$", "", area_cult10$V5, perl=TRUE), fixed=TRUE)

结果:

 [1] "11846.4" "6529.2"  "3282.7"  "616.0"   "1621.8"  "125.7"   "14.2"   
 [8] "401.6"   "455.5"   "11.7"    "160.4"   "79.1"    "37.6"    "29.6"   
[15] ""        "13.9"    "554.1"   "236.7"   "312.8"   "4.6"     "136.9"  
[22] "1374.4"  "1332.3"  "1281.8"  "3.7"     "5.0"     "18.4"    "23.4"   
[29] "42.0"    "2746.2"  "106.6"   "2100.4"  "267.8"   "258.4"   "13.1"   
[36] "23.5"    "11.6"    "310.2"  

gsub正则表达式值得特别关注:

  • (*UCP) - 强制执行该模式的PCRE动词
  • [\\s\\p{L}]+ - 匹配1 +空格或字母
  • | - 或(交替运营商)
  • \\W+$ - 字符串末尾有1个非字字符。

然后,sub(",", ".", x, fixed=TRUE)会将第一个,替换为.作为文字字符串,fixed=TRUE可以保存性能,因为它不需要编译正则表达式。