R gsub和两个空格和括号

问题描述 投票:0回答:1
library(tidyverse)
df <- data.frame(col1 = c("one space", "two  (spaces)"))
#>            col1
#> 1     one space
#> 2 two  (spaces)

[当我尝试用two (spaces)替换短语ts时,我简短地指出:

# Try #1
df %>% mutate(col1 = gsub("two  (spaces)", "ts", col1))
#>            col1
#> 1     one space
#> 2 two  (spaces)

# Try #2
df %>% mutate(col1 = gsub("two[:space:][:space:](spaces)", "ts", col1))
#>            col1
#> 1     one space
#> 2 two  (spaces)

我该如何正确执行?

第一次尝试,R Studio基本上总是将我的两个空格更改为一个选项卡。我不确定这是否是问题。我的第二次尝试感觉应该可行。不幸的是,看来R不在乎我的感受。

r regex gsub
1个回答
0
投票

我们可以使用fixed = TRUE,因为(是正则表达式中的元字符来捕获组

library(dplyr)
df %>% 
   mutate(col1 = gsub("two  (spaces)", "ts", col1, fixed = TRUE))
#      col1
#1 one space
#2        ts
© www.soinside.com 2019 - 2024. All rights reserved.