What is regular expression and how we use regular expression in R? Explain with example

686    Asked by Deepalisingh in Data Science , Asked on Nov 20, 2019
Answered by Deepali singh

Regular expressions is a general term which covers the idea of pattern searching, typically in a string (or a vector of strings).

For now we'll learn about two useful functions for regular expressions and pattern searching (we'll go deeper into this topic in general later on):

grepl(), which returns a logical indicating if the pattern was found

grep(), which returns a vector of index locations of matching pattern instances

For both of these functions you'll pass in a pattern and then the object you want to search. Let's see some quick examples:

text <- "Hi there, do you know who you are voting for?"

grepl('voting',text)

Output

TRUE

grepl('Hi',text)

Output

TRUE

grepl('Sammy',text)

Output

FALSE

Now let us define a vector to see the effect of expression

v <- c('a','b','c','d')

grep('a',v)

Output:

1

grep('c',v)

Output:

3



Your Answer

Interviews

Parent Categories