Learn R Programming

pater (version 1.0.0)

pathToRegexp: Build a regular expression for matching strings against pathnames

Description

Build a regular expression for matching strings against pathnames

Usage

pathToRegexp(
  path,
  end = TRUE,
  sensitive = FALSE,
  trailing = TRUE,
  delimiter = "/",
  ...
)

Value

A list with two elements: a regular expression and a list of keys.

Arguments

path

A character vector, TokenData, or a list of strings and TokenData objects.

end

A logical vector of length 1. Whether to add a construct to the regular expression to check for a complete end of string match. Defaults to TRUE.

sensitive

A logical vector of length 1. Whether resulting regex will be case sensitive. Defaults to FALSE.

trailing

A logical vector of length 1. Whether or not match trailing path. Defaults to TRUE.

delimiter

A character vector of length 1. Specifies the delimiter for the path segments. Defaults to "/"

...

Additional parameters for parse.

Examples

Run this code
path <- "/hello/world"
regex <- pathToRegexp(path)$pattern
grepl(regex,"/hello/world", perl = TRUE)
grepl(regex,"/hello/world/", perl = TRUE)

path <- "/hello/:world"
regex <- pathToRegexp(path)$pattern
grepl(regex, "/hello/world", perl = TRUE)
grepl(regex, "/hello/path", perl = TRUE)


# Taken from https://expressjs.com/en/guide/routing.html
path <- "/flights/:from-:to"
regex <- pathToRegexp(path)$pattern
grepl(regex, "/flights/a-b", perl = TRUE)
grepl(regex, "/flights/a-b/", perl = TRUE)

# Taken from https://expressjs.com/en/guide/routing.html
path <- "/users/:userId/books/:bookId"
regex <- pathToRegexp(path)$pattern
grepl(regex, "/users/1/books/2", perl = TRUE)
grepl(regex, "/users/1/books/2/", perl = TRUE)

path <- "/plantae/:genus.:species"
regex <- pathToRegexp(path)$pattern
grepl(regex, "/plantae/a.b", perl = TRUE)
grepl(regex, "/plantae/a.b/", perl = TRUE)

# Will match any route that starts with "/public/"
path <- "/public/*files"
regex <- pathToRegexp(path)$pattern
grepl(regex,"/public/format1", perl = TRUE)
grepl(regex,"/public/format2/format3", perl = TRUE)

# trailing
path <- "/user/:userId"
regex <- pathToRegexp(path, trailing = FALSE)$pattern
grepl(regex, "/user/1", perl = TRUE) # TRUE
grepl(regex, "/users/1/", perl = TRUE) # FALSE

# sensitive
path <- "/user"
regex <- pathToRegexp(path, sensitive = TRUE)$pattern
grepl(regex, "/user", perl = TRUE) # TRUE
grepl(regex, "/USER", perl = TRUE) # FALSE

# end
path <- "/users"
regex1 <- pathToRegexp(path, trailing = FALSE, end = FALSE)$pattern
regex2 <- pathToRegexp(path, trailing = FALSE, end = TRUE)$pattern
if(require("stringr")){
  str_extract("/users////", regex1) # "/users"
  str_extract("/users////", regex2) # NA
}

Run the code above in your browser using DataLab