Skip to contents

Switch function that will generate a regex pattern that will help extract parts of a string that we need. All of these functions are based on common patterns returned from Qualtrics Surveys.

Usage

srv_regex(
  type = c("inside_parentheses", "before_dash", "after_dash", "inside_brackets",
    "after_phrase", "a_or_x_digit"),
  phrase = NULL
)

Arguments

type

A character string. Possible values: "inside_parentheses", "before_dash", "after_dash", "inside_brackets", "after_phrase"

phrase

A character string. Phrase to be used with "everything_after_phrase" type parameter value.

Value

A regex string

Details

Currently there are 5 common patterns that are provided with this wrapper. Passing proper string to type argument allows you to extract each of them. The list below covers a few string examples, and which type should be used to get the correct regex:

  • To extract all the text in parentheses, i.e. "especially late" from "I like coffe (especially latte)", use srv_regex("inside_parentheses") to return the correct regex;

  • If you are working with a string like "Jaguar - Your favourite car brand", and you need a regex that will help you extract "Jaguar" - use srv_regex("before_dash");

  • The regular expression which you need to extract "RStudio" from "My favourite IDE - RStudio" is returned with: srv_regex("after_dash");

  • The correct regex to extract "Coca-Cola" from "My favourite brand is [Coca-Cola]" can be found with srv_regex("inside_brackets");

  • In case you are interested in the regular expression to extract the part of a string that comes after a certain phrase (i.e., "Heavy Metal" from "Your favourite music type. Select up to 3. Heavy Metal"), use srv_regex("after_phrase", "Select up to 3\\.").

Examples

library(stringr)

str_extract(
  string = "Disruptive partner (e.g., someone snoring)",
  pattern = srv_regex("inside_parentheses")
)
#> [1] "e.g., someone snoring"

str_extract(
  string = "Brand - Have you ever used [Brand]?",
  pattern = srv_regex("before_dash")
)
#> [1] "Brand"

str_extract(
  string = paste0(
    "[People prefer to live among people of the same race or ethnicity]",
    " Select up to 3 reasons."
  ),
  pattern = srv_regex("inside_brackets")
)
#> [1] "People prefer to live among people of the same race or ethnicity"

str_extract(
  string = paste(
    "Drag and drop in order of most preferred (top) to least ",
    "preferred (bottom). - Mentor-hello"
  ),
  pattern = srv_regex("after_dash")
)
#> [1] "Mentor-hello"

str_extract(
  string = "Which of the following...? phrase. Developing life skills",
  pattern = srv_regex("after_phrase", "phrase.")
)
#> [1] "Developing life skills"

str_remove(string = "m1_a2_variable_19", pattern = srv_regex("a_or_x_digit"))
#> [1] "m1_variable_19"