相关:将大写单词转换为标题大小写 https://stackoverflow.com/questions/51857207/convert-upper-case-words-to-title-case
一些使用从在线获取的字符串的代码的行为与我预期的不同,您可以通过运行以下命令来重现该问题:
library(xml2)
library(magrittr)
x <- xml2::read_html("https://poesie.webnet.fr/lesgrandsclassiques/Authors/B") %>%
gsub("^.*?<span>(Pierre-Jean de BÉRANGER)</span>.*$","\\1",.)
x # [1] "Pierre-Jean de BÉRANGER"
该字符串与"Pierre-Jean de BÉRANGER"
从页面源复制/粘贴,但是以下行为令我非常不安:
y <- "Pierre-Jean de BÉRANGER"
x == y # TRUE
identical(x, y) # TRUE
gsub("\\b([A-Z])(\\w+)\\b", "\\1\\L\\2", x, perl = TRUE) # [1] "Pierre-Jean de BÉRANGER"
gsub("\\b([A-Z])(\\w+)\\b", "\\1\\L\\2", y, perl = TRUE) # [1] "Pierre-Jean de Béranger"
grepl("\\bB\\w+", x, perl = TRUE) # FALSE
grepl("\\bB\\w+", y, perl = TRUE) # TRUE
grepl("\\bB\\w", x, perl = TRUE) # TRUE
grepl("\\bB\\w", y, perl = TRUE) # TRUE
If x
and y
是相同的,它们怎么会给出不同的输出?
?identical
:
测试两个物体是否安全可靠的方法exactly equal
Edit:
这是一个可观察到的差异:
Encoding(x) # "UTF-8"
Encoding(y) # "latin1"
我在跑R version 3.5.0
on Windows