使用 stringr 删除最后 space 之后的所有内容
Remove everything after last space with stringr
我有这样的数据:
df <- tribble(
~name, ~value,
"Jake Lake MLP", 10,
"Bay May CE", 5,
"Drake Cake Jr. DSF", 9.1,
"Sam Ram IR QQQZ", 1
)
我想要 trim 所有的名字,这样它们就是:
"Jake Lake",
"Bay May",
"Drake Cake Jr.",
"Sam Ram IR"
基本上删除最后一个 space 之后的所有内容。
我试过了:
df %>% mutate(name = str_replace(name, "\s.*$", ""))
但这不是我想要的!
我们可以使用sub
df %>%
mutate(name = sub("\s+[^ ]+$", "", name))
或str_replace
中的相同模式
df %>%
mutate(name = str_replace(name, "\s[^ ]+$", ""))
# A tibble: 4 × 2
# name value
# <chr> <dbl>
#1 Jake Lake 10.0
#2 Bay May 5.0
#3 Drake Cake Jr. 9.1
#4 Sam Ram IR 1.0
模式表示一个space(\s
)后跟一个或多个非白色space(否则它可以\S+
)直到字符串结束并且将其替换为空白 ""
。在 OP 的代码中,它是非特定的 (.*
)。
我有这样的数据:
df <- tribble(
~name, ~value,
"Jake Lake MLP", 10,
"Bay May CE", 5,
"Drake Cake Jr. DSF", 9.1,
"Sam Ram IR QQQZ", 1
)
我想要 trim 所有的名字,这样它们就是:
"Jake Lake",
"Bay May",
"Drake Cake Jr.",
"Sam Ram IR"
基本上删除最后一个 space 之后的所有内容。
我试过了:
df %>% mutate(name = str_replace(name, "\s.*$", ""))
但这不是我想要的!
我们可以使用sub
df %>%
mutate(name = sub("\s+[^ ]+$", "", name))
或str_replace
df %>%
mutate(name = str_replace(name, "\s[^ ]+$", ""))
# A tibble: 4 × 2
# name value
# <chr> <dbl>
#1 Jake Lake 10.0
#2 Bay May 5.0
#3 Drake Cake Jr. 9.1
#4 Sam Ram IR 1.0
模式表示一个space(\s
)后跟一个或多个非白色space(否则它可以\S+
)直到字符串结束并且将其替换为空白 ""
。在 OP 的代码中,它是非特定的 (.*
)。