本文介绍了删除字符串中的(不间断)空格字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题似乎很容易删除R中的字符串中的空格字符.但是,当我加载下表时,我无法删除两个数字之间的空格(例如11 846.4):

This question seems to make it easy to remove space characters in a string in R. However when I load the following table I'm not able to remove a space between two numbers (eg.11 846.4):

require(XML)
require(RCurl)
require(data.table)

link2fetch = 'https://www.destatis.de/DE/Themen/Branchen-Unternehmen/Landwirtschaft-Forstwirtschaft-Fischerei/Feldfruechte-Gruenland/Tabellen/ackerland-hauptnutzungsarten-kulturarten.html'

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

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

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

Why can't I remove the space in test[1]?Thanks for any advice! Can this be something else than a space character? Maybe the answer is really easy and I'm overlooking something.

推荐答案

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

You may shorten the test creation to just 2 steps and using just 1 PCRE regex (note the perl=TRUE parameter):

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正则表达式值得特别注意:

The gsub regex is worth special attention:

  • (*UCP)-将模式强制为Unicode识别的PCRE动词
  • [\\s\\p{L}]+-匹配1+个空格或字母字符
  • |-或(交替运算符)
  • \\W+$-字符串末尾有1个以上的非单词字符.
  • (*UCP) - the PCRE verb that enforces the pattern to be Unicode aware
  • [\\s\\p{L}]+ - matches 1+ whitespace or letter characters
  • | - or (an alternation operator)
  • \\W+$ - 1+ non-word chars at the end of the string.

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

Then, sub(",", ".", x, fixed=TRUE) will replace the first , with a . as literal strings, fixed=TRUE saves performance since it does not have to compile a regex.

这篇关于删除字符串中的(不间断)空格字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:57