R语言:提取包装规格中的数量、容量及计量单位组件
Got it, let's solve this problem step by step. You've already nailed extracting the item quantity, so let's focus on pulling out the single item volume and unit of measurement (UOM) from your pack vector using regular expressions in R.
1. Extract Single Item Volume
The volume is the numeric value immediately following the X in each string. We can target this with a regex that captures the digits right after X, ignoring any trailing characters:
pack <- c("1X7CL ML", "2X3ML CLose","24X33cl Ltront","24X1LTR CLear", "192X5cl mlow") # Extract volume volume <- as.numeric(gsub(".*X(\\d+).*", "\\1", pack))
How this works:
.*Xmatches any characters up to and including theX(\\d+)captures one or more digits (this is our volume value).*matches any remaining characters after the volume- We replace the entire string with the captured digits (
\\1) and convert to numeric
2. Extract Unit of Measurement (UOM)
We need to capture the first occurrence of CL, ML, or LTR (case-insensitive) in each string. Let's use your UOM vector to build a flexible regex pattern, then extract and standardize the UOM to match your expected output:
Option 1: Base R (no extra packages)
UOM <- c("CL","ML","LTR") # Build regex pattern to match any UOM (case-insensitive) uom_pattern <- paste(toupper(UOM), collapse = "|") # Extract UOM, standardize to uppercase uom <- gsub(paste0(".*(", uom_pattern, ").*"), "\\1", toupper(pack))
Option 2: Using stringr (cleaner syntax)
If you don't mind using the stringr package, this approach is more straightforward:
library(stringr) uom <- str_extract(toupper(pack), paste(toupper(UOM), collapse = "|"))
How this works:
toupper(pack)converts all characters to uppercase to handle case variability (likecl,Ltr)paste(toupper(UOM), collapse = "|")creates a regex pattern likeCL|ML|LTRto match any valid UOMstr_extractpulls the first matching UOM from each string, while the base Rgsubapproach replaces the entire string with the captured UOM
3. Verify All Results
Let's combine all three vectors into a data frame to confirm we match your expected output:
# Quantity extraction (your existing code) quantity <- as.numeric(gsub("(.*?)(X.*)", "\\1", pack)) # Combine into data frame result <- data.frame( quantity = quantity, volume = volume, uom = uom ) print(result)
Output:
quantity volume uom 1 1 7 CL 2 2 3 ML 3 24 33 CL 4 24 1 LTR 5 192 5 CL
This exactly matches the expected results you listed!
内容的提问来源于stack exchange,提问作者Ashwin

