Apoorva Srivastava
Apoorva Srivastava

Reputation: 21

Special character matching in r using grep

If I have a sentence separated by spaces

s<-("C java","C++ java")
grep("C",s)

gives output as
[1] [2] while I only require [1] How to do that? ( I have used c\++ to identify c++ separately but matching with C gives [1] and [2] both as the output)

Upvotes: 1

Views: 62

Answers (2)

akrun
akrun

Reputation: 887291

If we want to match 1 only, then we can use the start (^) and end ($) of the string to denote that there are no characters after or before 'C'

grep("^C$",s)
#[1] 1

data

s<- c("C","C++","java")

Upvotes: 2

drJones
drJones

Reputation: 1233

s<-c("C","C++","java")    
which(s %in% "C")

grep() gives a positive result for any match within a string

Upvotes: 0

Related Questions