Using Glue for String Search

glue

#1

Hi,

I am using glue to take a vector of words and condense them to a string with a | to separate them
I want to check if a string I am checking is contained within my made up example "VWBEA0633M1234567"
The string is present but I seem to be getting the characters "" at the start and end of the string which is causing a FALSE detection on my lookup
Does anyone know where I'm going wrong?

library(glue)
library(tidyverse)

# https://stackoverflow.com/questions/42734547/generating-random-strings
set.seed(999)
myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

ref_data <- myFun(20) %>% 
  tibble() %>% 
  select(key_word = ".")

find <-  glue('"{glue_collapse(ref_data$key_word, sep = "|")}"')
str_detect("KXCZI4536E123456789", find)
#> [1] FALSE

as.character(find)
#> [1] "\"KXCZI4536E|PQUUQ9578V|COTSN2595W|WIMYL9243C|UVJOC9594W|DVHMF4753Y|POQWD6428W|CQGWZ1415U|KVDKQ4734M|QLBIM5696L|HCTAP6113D|OFQIF2211C|ANDJA7149C|ZPWLS2847L|COESN1005K|UWPEE8178I|EVBSS6683I|VUTMN0134B|DALCM2859V|BLVGX9246H\""

Created on 2018-12-06 by the reprex package (v0.2.1)


#2

You seem to have two sets of quotations in your glue string, removing the double quotes does what I think you were expecting.

library(glue)
library(tidyverse)

# https://stackoverflow.com/questions/42734547/generating-random-strings
set.seed(999)
myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

ref_data <- myFun(20) %>% 
  tibble() %>% 
  select(key_word = ".")

find <-  glue('{glue_collapse(ref_data$key_word, sep = "|")}')
str_detect("KXCZI4536E123456789", find)
#> [1] TRUE

Created on 2018-12-06 by the reprex package (v0.2.1)


#3

Hi @jimhester

Thank you very much for your quick reply. Its now working exactly as I need

Thanks