Ruby字符串拆分技术咨询:按每个首个空格实现特殊格式拆分
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
gflag in JS orfindallin 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

