带特殊字符的grep [英] grep with special characters

查看:743
本文介绍了带特殊字符的grep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  s < -  c(A ,B,C *,D,E *)
grep(*,s)

[1] 1 2 3 4 5

这不起作用。我可以理解,因为它是一个特殊的字符。

当我阅读这里,我决定在星号之前使用\。但是这给了我一个错误:

$ $ p $ grep(\ *,s)
错误:'\ *'是字符串中无法识别的转义符\ *

我做错了什么

解决方案

你需要两次转义特殊字符,一次为R,一次为正则表达式:

  grep('\\ *',s)


I want to find the elements that contains star character in the following vector.

s <- c("A","B","C*","D","E*")
grep("*",s)

[1] 1 2 3 4 5

This is not working. I can understand that since it is a special character.
When I read here, I decided to use "\" before star character. But that gave me an error:

grep("\*",s)
Error: '\*' is an unrecognized escape in character string starting ""\*"

What am I doing wrong?

解决方案

You need to escape special characters twice, once for R and once for the regular expression:

grep('\\*', s)

这篇关于带特殊字符的grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆