在每个单词的开头添加一个字符

时间:2018-03-21 11:54:20

标签: r regex

我有一个字符串向量,想在每个字符串中的每个单词之前添加一个+。

strings <- c('string one', 'string two', 'string three')
strings_new <- str_replace_all(strings, "\\b\\w", '+')
string_new

不幸的是,这是替换第一个字符,而不是添加+符号。我不太熟悉正则表达式,知道如何解决这个问题。

任何帮助都会很棒。

由于

4 个答案:

答案 0 :(得分:7)

使用捕获的组是执行此操作的一种方法。使用括号进行分组并使用\\1进行回忆。

strings_new <- str_replace_all(strings, "(\\b\\w)", '+\\1')
strings_new
[1] "+string +one"   "+string +two"   "+string +three"

答案 1 :(得分:3)

您可以使用基础R 解决方案,使用匹配起始字词边界的PCRE正则表达式[[:<:]],这是非字词和字词字符之间的位置:

strings <- c('string one', 'string two', 'string three')
gsub("[[:<:]]", "+", strings, perl=TRUE)
# => [1] "+string +one"   "+string +two"   "+string +three"

或者,您可以使用(\w+)(匹配并捕获第1组中的任何一个或多个字符,即字母,数字或_)TRE正则表达式替换为{{1和替换后向引用+来恢复输出中消耗的字符:

\1

请注意,这里不需要单词边界,因为char匹配的第一个单词已经在单词边界处,并且由于gsub("(\\w+)", '+\\1', strings) # => [1] "+string +one" "+string +two" "+string +three" 量词,后续单词chars将被消耗。请参阅regex demo

使用基于+的ICU正则表达式,您可以使用

str_replace_all

> str_replace_all(strings, "\\w+", '+\\0') [1] "+string +one" "+string +two" "+string +three" 是对整个比赛的替代反向引用。

答案 2 :(得分:1)

如下所示,您可以使用正则表达式\b(?=\w)perl=T,在没有捕获组的情况下(正如其他人所示)执行此操作。

See code in use here

strings <- c('string one', 'string two', 'string three')
gsub("\\b(?=\\w)", "+", strings, perl=T)

结果

[1] "+string +one"   "+string +two"   "+string +three"

答案 3 :(得分:0)

另一种方法是将strsplit()paste0()结合使用:

res <- lapply(strsplit(strings, " "), function(x) paste0("+", x))
sapply(res, paste0, collapse = " ")
# [1] "+string +one"   "+string +two"   "+string +three"

对某些人来说,优点可能是你不必与正则表达式搏斗。但是,我总是更喜欢Jasbner和Wictor的直接正则表达式语句

相关问题