Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect a pattern in String using str_detect

Tags:

r

stringr

I'm trying to detect if a string contains a specific pattern using str_detect. The pattern I have is a series of "...." - exact number of dots is unknown. I'm trying to use str_detect as below....

However, in this particular case, str_detect returns TRUE. Wondering where I am doing it wrong and if str_detect is the right function to use at all? Hoping someone here can help?

library(stringr)
dot_pat="\\.........................";
str="The primary.objective is of the study."
str_detect(str,dot_pat)

This returns TRUE. I'm expecting FALSE since the dots in str do not follow the pattern.

Thanks in advance, simak

like image 266
BRZ Avatar asked Jul 07 '26 01:07

BRZ


2 Answers

Your pattern means: a dot (\\.) followed by 24 symbols. So this matches: ".objective is of the stu".

If you want to detect, say 10 dot symbols, use a pattern like this: dot_pat="\.{10}"

str_detect("The primary.objective is of the study.", "\\.{10}")
str_detect("hello..........world", "\\.{10}")
like image 142
Karl Forner Avatar answered Jul 09 '26 16:07

Karl Forner


Another much poorer approach would be to escape every single "." which Sean indicates is regex for "any character" unless it is escaped.

paste(rep("\\.", 10), collapse = "")
## This gives
## [1] "\\.\\.\\.\\.\\.\\.\\.\\.\\.\\."


str_detect("The primary.objective is of the study.", paste(rep("\\.", 10), collapse = ""))
str_detect("hello..........world", paste(rep("\\.", 10), collapse = ""))
like image 45
Tyler Rinker Avatar answered Jul 09 '26 15:07

Tyler Rinker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!