首页 > 解决方案 > 大写基本方向,对 R 中的所有其他内容使用标题大小写

问题描述

我有一个大写的地址列表。我想转换为标题大小写,但保留基本方向的大写,例如 NE、NW、SE、SW。

address <- c("14615 SE CREEKSIDE DRIVE")
stringr::str_to_title(address)

# this returns 
14615 Se Creekside Drive

# desired result
14615 SE Creekside Drive

标签: rregexcase-sensitiveuppercasestringr

解决方案


尝试:

> gsub("\\b([A-Z])(\\w{2,})", "\\1\\L\\2" , "14615 SE CREEKSIDE DRIVE", perl=true)
[1] "14615 SE Creekside Drive"

正则表达式分解:

  • \b匹配单词边界
  • ([A-Z])匹配一个大写字母
  • (\w{2,})匹配两个以上的单词字符

推荐阅读