这是我的看法,其中还包括一个非英语解决方案(我自己是斯堪的纳维亚人,但我认为它适用于很多不同的语言。
用英语很容易,而且更多地涉及其他语言。
基本上,我从字典文件 (*.dic) 中添加了我能找到的所有非英文字母,例如 ÅÆÅ,并使用它来代替 \W 和 \w。然而,使用单词边界特殊字符“\b”会搞砸事情,所以简单的解决方案就是不使用它。简单地排除它不会对我的数据造成问题,但可能存在可能成为问题的边缘情况,因此请小心并查看结果。
# with english chars it is 'quite' easy, but it can't deal with the last element
name <- c('John Dean', 'PETER Lemon', 'Simon Says', 'Åse Æsel')
searchstring <- '\\W*\\b(\\w)\\w*' # the \\b might not be a good idea, depending on the strings in question
searchstring <- '\\W*(\\w)\\w*'
gsub(searchstring, '\\1', name,perl=T)
# With other languages it gets more involved.
name <- c('John Dean', 'Lille ãder', 'Åse Æsel', 'Henrik d. 9')
notall_wordchars <- '[^A-Za-z0-9_ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ]'
all_wordchars <- '[A-Za-z0-9_ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ]'
searchstring <- paste0(notall_wordchars, '*',
'(', all_wordchars, ')', all_wordchars, '*')
gsub(searchstring, '\\1', name,perl=T)