This R package provides 4 tiny regex tools to extract, match, and
replace named regex groups in strings. It contains in addition to 3
functions groups()
, match_group()
and
replace_group()
a R6
class
Replacer
which is thought as the main interface of this
package.
You can install this package by installing it from CRAN or from this GitHub repository.
# install directly from CRAN
install.packages("regreplaceR")
# or install directly from this github repository
# install the devtools package if not already installed
install.packages("devtools")
# install the package directly from this repository
::install_github("gwangjinkim/regreplaceR") devtools
The package offers three core functions to interact with strings using regular expressions with named groups:
Additionally, it includes an R6 class called Replacer that encapsulates these functionalities for a more object-oriented approach to regex-based operations.
I couldn’t use match()
and replace()
as
generic functions, because there are already generic functions which
require a specific set of arguments. By using an R6 class, I was free to
choose the arguments for match()
and
replace()
.
This function extracts all named groups from a string based on a provided regex pattern.
<- "(?P<name>\\w+) is (?P<age>\\d+)"
pattern <- "Jane is 25"
s <- groups(pattern, s)
result
# Output:
# $name
# [1] "Jane"
#
# $age
# [1] "25"
Extract the value of a specific named group from the string.
<- "(?P<name>\\w+) is (?P<age>\\d+)"
pattern <- "Jane is 25"
s <- match_group(pattern, s, "name")
name
# Output:
# [1] "Jane"
Replace the value of a specific named group with a new string.
<- "(?P<name>\\w+) is (?P<age>\\d+)"
pattern <- "Jane is 25"
s <- replace_group(pattern, s, "name", "John")
modified
# Output:
# [1] "John is 25"
The Replacer class provides an object-oriented approach to regex-based operations. It allows you to create an instance with a specific regex pattern and then use it to match or replace named groups in strings.
# Create a new Replacer object
<- Replacer$new(pattern = ".*?_(?P<date>\\d{8}-\\d{6})(?P<ext>\\..+$)")
r
# Match a group within a string
<- r$match("file_20230905-123456.txt", "date")
date
# Replace the value of a matched group
<- r$replace("file_20230905-123456.txt", "date", "20240905-123456") modified_string
This package is licensed under the MIT License. See LICENSE for details.
Happy regexing! If you have any questions or find any bugs, please feel free to open an issue on the GitHub repository.