Replacer {regreplaceR} | R Documentation |
The Replacer
class encapsulates regex operations using named groups.
It allows matching and replacing based on named groups in a regex pattern.
This class provides methods to match and replace parts of a string based on named groups in regular expressions.
re
A compiled regular expression pattern.
new()
Create a new Replacer object with a regex pattern.
Replacer$new( pattern = ".*?_(?P<date>\\d{8}-\\d{6}( \\(1\\))*)(?P<ext>\\..+$)" )
pattern
A character string with a regex pattern that includes named groups.
A new Replacer
object.
r <- Replacer$new(pattern=".*?_(?P<date>\\d{8}-\\d{6}( \\(1\\))*)(?P<ext>\\..+$)")
match()
Match a string and extract a group by its name.
This method matches the string using the regex pattern and extracts the value
of the group specified by group_name
.
Replacer$match(s, group_name)
s
A character string to match against the regex pattern.
group_name
The name of the group to extract from the match.
The matched value of the group or NULL
if not found.
r <- Replacer$new(pattern=".*?_(?P<date>\\d{8}-\\d{6})(?P<ext>\\..+$)") r$match("file_20230905-123456.txt", "date")
replace()
Replace the value of a matched group with a replacement string.
This method replaces the value of the matched group specified by group_name
with the replacement
string in the input string s
.
Replacer$replace(s, group_name, replacement)
s
A character string to perform the replacement on.
group_name
The name of the group to be replaced.
replacement
The replacement string.
A modified string with the group replaced by the replacement.
r <- Replacer$new(pattern=".*?_(?P<date>\\d{8}-\\d{6})(?P<ext>\\..+$)") r$replace("file_20230905-123456.txt", "date", "20240905-123456")
clone()
The objects of this class are cloneable with this method.
Replacer$clone(deep = FALSE)
deep
Whether to make a deep clone.
# Create a new Replacer object
r <- Replacer$new(pattern = ".*?_(?P<date>\\d{8}-\\d{6})(?P<ext>\\..+$)")
# Match a group within a string
r$match("file_20230905-123456.txt", "date")
# Replace the value of a matched group
r$replace("file_20230905-123456.txt", "date", "20240905-123456")
## ------------------------------------------------
## Method `Replacer$new`
## ------------------------------------------------
r <- Replacer$new(pattern=".*?_(?P<date>\\d{8}-\\d{6}( \\(1\\))*)(?P<ext>\\..+$)")
## ------------------------------------------------
## Method `Replacer$match`
## ------------------------------------------------
r <- Replacer$new(pattern=".*?_(?P<date>\\d{8}-\\d{6})(?P<ext>\\..+$)")
r$match("file_20230905-123456.txt", "date")
## ------------------------------------------------
## Method `Replacer$replace`
## ------------------------------------------------
r <- Replacer$new(pattern=".*?_(?P<date>\\d{8}-\\d{6})(?P<ext>\\..+$)")
r$replace("file_20230905-123456.txt", "date", "20240905-123456")