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

正则表达式拆分字符串:保留方括号内按键内容的实现求助

Solution for Splitting String with Regular Characters and Bracketed Key Names

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

  1. First, load the stringr package if you haven't already:

    library(stringr)
    
  2. Define your input string:

    x <- "cd/etc/init[BKSP][BKSP]it.d[ENTER]"
    
  3. Use str_extract_all to 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]]
    
  4. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:34:48