正则表达式拆分字符串:保留方括号内按键内容的实现求助
Got it, let's tackle this problem. You need to split a string such that every regular character is separated into its own element, while bracketed key identifiers (like [BKSP] or [ENTER]) are preserved as single elements. Here's a clean regex-based approach using R's stringr package:
Step-by-Step Implementation
First, load the
stringrpackage if you haven't already:library(stringr)Define your input string:
x <- "cd/etc/init[BKSP][BKSP]it.d[ENTER]"Use
str_extract_allto capture both bracketed key names and individual regular characters:# Match either bracketed key names (e.g., [BKSP]) or single any character raw_matches <- str_extract_all(x, "\\[[A-Z]+\\]|.")[[1]]Clean up the bracketed matches to remove the square brackets:
final_result <- sapply(raw_matches, function(item) { if (str_detect(item, "^\\[.*\\]$")) { # Remove the first and last characters (the square brackets) str_sub(item, 2, -2) } else { item } })
What the Regex Does
\\[[A-Z]+\\]: Matches any sequence of uppercase letters wrapped in square brackets (this targets your key names like[BKSP]or[ENTER]).|.: The pipe (|) acts as an OR operator, and.matches any single character (all the regular text characters you want to split individually).
Result Verification
If you print final_result, you'll get exactly the output you're looking for:
> final_result [1] "c" "d" "/" "e" "t" "c" "/" "i" "n" "i" "t" "BKSP" "BKSP" "i" "t" "." "d" "ENTER"
Alternative One-Liner
If you prefer a more concise version, you can combine the extraction and cleanup using lookaround assertions to directly capture the text inside brackets:
final_result <- str_extract_all(x, "(?<=\\[)[A-Z]+(?=\\])|.")[[1]]
This uses positive lookbehind ((?<=\\[)) and positive lookahead ((?=\\])) to grab only the key name text without the surrounding brackets, alongside individual regular characters.
内容的提问来源于stack exchange,提问作者TuD

