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

如何拆分连续2个及以上空格为换行,同时保留单个空格不变?

Solution for Replacing Multiple Spaces with Line Breaks in R

Got it, let's solve this problem where we need to swap two or more consecutive spaces with line breaks, while keeping single spaces exactly as they are. Here's a straightforward way to do it in R using regular expressions:

Step 1: Define Your Text

First, let's set up some test text that includes both single spaces (like your example) and multiple consecutive spaces to verify the solution works:

text <- c(
  "Hello, how are you doing?",  # Only single spaces (your example)
  "Hi   there!  This is a test with multiple   spaces."  # Has 3, 2, and 3 consecutive spaces
)

Step 2: Process the Text with gsub()

We'll use R's gsub() function to find all instances of two or more consecutive spaces and replace them with a line break (\n):

# Replace 2+ consecutive spaces with line breaks
processed_text <- gsub("\\s{2,}", "\n", text)
  • \\s{2,}: This regex pattern matches 2 or more consecutive whitespace characters (spaces, tabs, etc.). If you want to target only actual spaces (not tabs), use " {2,}" instead (note the space before the curly braces).
  • "\n": This is the line break character we're replacing the multiple spaces with.

Step 3: Verify the Results

Let's print out the processed text to check:

# Check the first text (your example) - should match original
cat(processed_text[1], "\n\n")

# Check the second text - should have line breaks where multiple spaces were
cat(processed_text[2])

Output:

Hello, how are you doing? 

Hi 
there! 
This is a test with multiple 
spaces.

As you can see, your original example with only single spaces stays exactly the same, while the text with multiple spaces gets line breaks in the right spots.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:35:47