本文介绍了如何逃脱方括号“]"在R中的正则表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中使用gsub替换我正在处理的某些字符串中的一堆怪异字符.一切正常,除非每当我输入]"时,它都会使整个操作无济于事.我正在像gsub("[\\?\\*\\]]", "", name)一样使用\\,但仍然无法正常工作.这是我的实际示例:

I'm trying to use gsub in R to replace a bunch of weird characters in some strings I'm processing. Everything works, except whenever I throw in "]" it makes the whole thing do nothing. I'm using \\ like gsub("[\\?\\*\\]]", "", name) but it's still not working. Here's my actual example:

name <- "R U Still Down? [Remember Me]"

我想要的是:names"R U Still Down Remember Me"

当我这样做时: names <- gsub("[\\(\\)\\*\\$\\+\\?'\\[]", "", name)它成功了,我得到了"R U Still Down Remember Me]"

when I do: names <- gsub("[\\(\\)\\*\\$\\+\\?'\\[]", "", name)it semi-works and I get "R U Still Down Remember Me]"

但是当我这样做时: names <- gsub("[\\(\\)\\*\\$\\+\\?'\\[\\]]", "", name)什么都没发生. (即我得到"R U Still Down? [Remember Me]")

but when I do: names <- gsub("[\\(\\)\\*\\$\\+\\?'\\[\\]]", "", name)nothing happens. (i.e. I get "R U Still Down? [Remember Me]")

有什么想法吗?我已经尝试过改变事物的顺序,等等.但是我似乎无法弄清楚.

Any ideas? I've tried switching around the order of things, etc. But I can't seem to figure it out.

推荐答案

只需启用perl=TRUE参数.

> gsub("[?\\]\\[*]", "", name, perl=T)
[1] "R U Still Down Remember Me"

并仅转义所需的字符.

> gsub("[()*$+?'\\[\\]]", "", name, perl=T)
[1] "R U Still Down Remember Me"

这篇关于如何逃脱方括号“]"在R中的正则表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 21:30