Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grepl for a period "." in R?

Tags:

regex

r

grepl

Lets say I have a string "Hello." I want to see if this string contains a period:

text <- "Hello."
results <- grepl(".", text)

This returns results as TRUE, but it would return that as well if text is "Hello" without the period.

I'm confused, I can't find anything about this in the documentation and it only does this for the period.

Any ideas?

like image 273
marc Avatar asked Oct 24 '13 15:10

marc


People also ask

What does Grepl () do in R?

The grepl() stands for “grep logical”. In R it is a built-in function that searches for matches of a string or string vector. The grepl() method takes a pattern and data and returns TRUE if a string contains the pattern, otherwise FALSE.

How do you match periods in regex?

Any character (except for the newline character) will be matched by a period in a regular expression; when you literally want a period in a regular expression you need to precede it with a backslash. Many times you'll need to express the idea of the beginning or end of a line or word in a regular expression.

What is the difference between grep and Grepl in R?

The grep and grepl functions use regular expressions or literal values as patterns to conduct pattern matching on a character vector. The grep returns indices of matched items or matched items themselves while grepl returns a logical vector with TRUE to represent a match and FALSE otherwise.

What does %s mean in regex?

The Difference Between \s and \s+ For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.


1 Answers

See the differences with these examples

 > grepl("\\.", "Hello.")
[1] TRUE
> grepl("\\.", "Hello")
[1] FALSE

the . means anything as pointed out by SimonO101, if you want to look for an explicit . then you have to skip it by using \\. which means look for a .

R documentation is extensive on regular expressions, you can also take a look at this link to understand the use of the dot.

like image 187
Jilber Urbina Avatar answered Oct 14 '22 07:10

Jilber Urbina