The “regmatches” Function in R

  • Package: Base R (No specific package, it’s a built-in function)

  • Purpose: To extract or replace matched substrings based on the output of functions like regexpr or gregexpr.

  • General Class: String Manipulation

  • Required Argument(s):

    • x: A character vector from which to extract or replace matched substrings.

    • m: A list of match objects, typically obtained from functions like regexpr or gregexpr.

  • Notable Optional Argument:

    • invert: Default is FALSE. If TRUE the regmatches function returns the non-matched portion of the substrings.

  • Example:

  • # Example usage
    sentence <- "The quick brown fox jumps over the lazy dog."

    # Find the position of the first occurrence of "fox" (case-sensitive)
    pattern_position <- regexpr(pattern = "fox", text = sentence)

    # Extract the matched substring using regmatches
    matched_substring <- regmatches(sentence, pattern_position)

    print(matched_substring)

  • In this example, the regmatches function extracted the word “fox” using the index created by the regexpr function.

Previous
Previous

The “tolower” Function in R

Next
Next

The “regexec” Function in R