在R中提取文本及解压API传入的GZIP压缩Base64数据方法问询
Hey there! Let's tackle your two R questions one by one with actionable code snippets:
Text extraction covers a few common scenarios—here are the most practical methods for each:
Extract specific patterns from strings
For regex-based extraction, you can use base R functions or the more intuitivestringrpackage. Here's how:# Base R approach: Extract an email from a sample string sample_text <- "Reach me at jose@example.com for follow-ups" email_pattern <- "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b" extracted_email <- regmatches(sample_text, gregexpr(email_pattern, sample_text))[[1]] print(extracted_email) # Output: "jose@example.com" # stringr approach (install first with install.packages("stringr")) library(stringr) str_extract(sample_text, email_pattern)Extract content from text files
First read the file, then filter or extract using regex:# Read a text file into a vector of lines file_lines <- readLines("your_target_file.txt") # Extract all lines containing "error" (case-insensitive) error_lines <- file_lines[grepl("error", file_lines, ignore.case = TRUE)] print(error_lines)Extract text from HTML/XML
Use thervestpackage for web scraping or structured document parsing:# Install package first: install.packages("rvest") library(rvest) # Extract all paragraph text from a sample webpage page <- read_html("https://example.com") paragraph_text <- page %>% html_elements("p") %>% html_text() print(paragraph_text)
Your Java code first GZIP-compresses the string then encodes it to Base64. To reverse this in R, we need to decode the Base64 string first, then decompress the raw bytes. Here's a working example:
# First, install the required package if you haven't: install.packages("base64enc") library(base64enc) # Example encoded data (matches "who are you" from your Java code) encoded_data <- "H4sIAAAAAAAAAEtUKC4pysxLBwCMN9M1NQAAAA=" # Step 1: Decode Base64 to raw bytes raw_compressed <- base64decode(encoded_data) # Step 2: Decompress the GZIP bytes # Create a connection to the raw bytes, wrap it in a GZIP handler con <- rawConnection(raw_compressed, open = "rb") decompressed_text <- readLines(gzcon(con), warn = FALSE) close(con) # Check the result print(decompressed_text) # Output: "who are you"
If you're working with non-text binary data instead of a string, replace readLines() with readBin() to handle the raw bytes appropriately.
内容的提问来源于stack exchange,提问作者Jose

