Skip to contents

Lookarounds allow you to position a regular expression to more specificity.

Usage

create_lookaround(pattern, lookaround_pattern, position, negate = FALSE)

Arguments

pattern

String. Pattern that you wish to add a look around to

lookaround_pattern

String. Pattern that you wish to look for.

position

String. One of 'before', 'after', 'ahead', or 'behind'. Capitalization doesn't matter

negate

Logical. allows you to exclude cases where look around is detected.

Value

Returns a string that can be used as a regular expression

Examples


# Here is a string with three patterns of digits
text <- "cars123ruin456cities789"

# To extract the first one we can use this pattern
stringr::str_extract(text, "\\d{3}")
#> [1] "123"
# or
create_lookaround("\\d{3}", "cars", "before") |>
stringr::str_extract(string=text)
#> [1] "123"

# To exclude the first one we can write
create_lookaround("\\d{3}", "cars", "before", negate=TRUE) |>
stringr::str_extract_all(string=text)
#> [[1]]
#> [1] "456" "789"
#> 

# To extract the second one we can write
 create_lookaround("\\d{3}", "ruin", "before") |>
stringr::str_extract(string=text)
#> [1] "456"

# or

create_lookaround("\\d{3}", "cities", "after") |>
stringr::str_extract(string=text)
#> [1] "456"