You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中提取文本及解压API传入的GZIP压缩Base64数据方法问询

Hey there! Let's tackle your two R questions one by one with actionable code snippets:

1. Text Extraction in R

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 intuitive stringr package. 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 the rvest package 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)
    
2. Decompressing GZIP-compressed Base64 Data in R

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:46:40