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

Ruby字符串拆分技术咨询:按每个首个空格实现特殊格式拆分

Solution to Split String with Preserved Standalone Spaces

Got it, let's work through this problem. You want to split the string "AB C D E F" into an array where standalone spaces are kept as separate elements (matching your target format ["AB", "C", " ", "D", "E", " ", "F"]), right? The standard split methods fall short here—they either strip out all spaces or only split on the first one, which doesn't fit your needs.

The key is to use a regular expression to match exactly what we want to keep instead of splitting on what we don't. This lets us capture both sequences of non-space characters and individual spaces as distinct array elements.

Example in JavaScript

const str = "AB C D E F";
const result = str.match(/\S+| /g);
console.log(result); // Output: ["AB", " ", "C", " ", "D", " ", "E", " ", "F"]

Example in Python

import re
input_str = "AB C D E F"
result = re.findall(r'\S+| ', input_str)
print(result) # Output: ['AB', ' ', 'C', ' ', 'D', ' ', 'E', ' ', 'F']

How This Works

  • \S+: Matches one or more non-space characters (grabs sequences like "AB", "C", "D" that we want to keep as single elements)
  • | : Acts as an "or" operator, matching a single space character to preserve it as its own element
  • The global match (via g flag in JS or findall in Python) ensures we capture every occurrence of either pattern across the entire string

If your input has consecutive spaces and you want to keep each as a separate element, this method handles that too. For example, "AB C" would become ["AB", " ", " ", "C"].

内容的提问来源于stack exchange,提问作者cooltop101

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:47:51