如何使用 stringr 函数替换精确的字符串? [英] How to replace an exact string using stringr functions?
问题描述
我正在尝试使用 stringr
函数替换列中的确切字符串.
I'm trying to replace exact strings in a column using stringr
functions.
我试用的数据集是这样的:
The dataset I try it on is this:
data <- data.frame(
column = c("Value", "Values", "Value", "Values")
)
data
column
1 Value
2 Values
3 Value
4 Values
我想用值"替换值".我尝试了 str_replace(data$column, "Value", "Values")
,但这会产生以下不需要的替换:
I want to replace "Value" with "Values". I tried str_replace(data$column, "Value", "Values")
, but this creates the following unwanted replacements:
[1] "Values" "Valuess" "Values" "Valuess"
我希望输出为:
[1] "Values" "Values" "Values" "Values"
推荐答案
以下是使用正则表达式的几种可能性:
Here are a few possibilities using regular expressions:
x <- c("value", "values")
str_replace(x, "value$", "values") #method 1
str_replace(x, "value\\b", "values") #method 2
str_replace(x, "value(?!s)", "values") #method 3
以上所有返回相同的
[1] "values" "values"
简短说明:第一种方法在字符串末尾查找值".符号 $
匹配字符串的结尾.
A short explanation: the first method looks for 'value' at the end of a string. The symbol $
matches the end of the string.
第二种方法查找值",然后是单词边界.
The second method looks for 'value' followed by a word boundary.
第三种方法查找value"后跟除符号s"之外的任何内容.
The third method looks for 'value' followed by anything but the symbol 's'.
您可以找到有关 stringr 和正则表达式的有用备忘单此处.希望这会有所帮助.
You can find a helpful cheat sheet about stringr and regular expressions here. Hope this helps.
这篇关于如何使用 stringr 函数替换精确的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!