在Linux上的R中删除字符串中的(不间断)空格字符

and*_*har 1 html regex linux string r

这个问题似乎很容易删除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?
Run Code Online (Sandbox Code Playgroud)

为什么不能删除其中的空格test[1]?感谢您的任何建议!可以是空格字符吗?也许答案真的很简单,但我却忽略了某些事情。

Wik*_*żew 5

您可以test仅使用1个PCRE正则表达式(请注意perl=TRUE参数)将创建过程缩短到仅2个步骤:

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

结果:

 [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"  
Run Code Online (Sandbox Code Playgroud)

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

  • (*UCP) -强制模式识别Unicode的PCRE动词
  • [\\s\\p{L}]+ -匹配1个以上空格或字母字符
  • | -或(交替运算符)
  • \\W+$ -字符串末尾的1+个非单词字符。

然后,sub(",", ".", x, fixed=TRUE)将第,一个替换为.as文字字符串,fixed=TRUE因为不必编译正则表达式,因此可以节省性能。