r - Trying to figure out regular expression in R for sub()
问题描述
I'm trying to use regular expression in a sub() function in order to replace all the "\" in a Vector
I've tried a number of different ways to get R to recognize the "\":
- I've tried "
\\\
" but I keep getting errors. - I've tried "
\.*
" - I've tried "
\\\.*
"
data.frame1$vector4 <- sub(pattern = "\\\", replace = ", data.frame1$vector4)
The \
that I am trying to get rid of only appears occasionally in the vector and always in the middle of the string. I want to get rid of it and all the characters that follow it.
The error that I am getting
Error: '\.' is an unrecognized escape in character string starting "\."
Also I'm struggling to get Stack to print the "\" that I am typing above. It keeps deleting them.
解决方案
1) 4 backslashes To insert backslash into an R literal string use a double backslash; however, a backslash is a metacharacter for a regular expression so it must be escaped by prefacing it with another backslash which also has to be doubled. Thus using 4 backslashes will be needed in the regular expression.
s <- "a\\b\\c"
nchar(s)
## [1] 5
gsub("\\\\", "", s)
## [1] "abc"
2) character class Another way to effectively escape it is to surround it with [...]
gsub("[\\]", "", s)
## [1] "abc"
3) fixed argument Perhaps the simplest way is to use fixed=TRUE
in which case special characters will not be regarded as regular expression metacharacters.
gsub("\\", "", s, fixed = TRUE)
## [1] "abc"
推荐阅读
- visual-studio - 关闭所有,但固定和这个?
- java - PowerMockito 验证永远不会调用静态方法
- grails - 如何通过模拟对象并期待一些预期结果来编写 Spock 单元测试
- corda - 我们应该如何升级一个由一个 DL 参与者拥有但有一个包含多个参与者的参与者列表的状态?
- ruby - 数组意外多重赋值
- continuous-integration - CircleCI:ESLint 在 CI 上返回退出代码 0 尽管测试失败
- javascript - 如果从数据库中获取的数据是!=“Detained”,如何调用函数
- javascript - Javascript - Firebase 子键
- c# - jQuery ajax 从代码隐藏中获取表格
- java - Log4j 的 PropertyConfigurator 不再存在?