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

如何将字符串中任意长度的连续空格替换为单个指定字符?

实现连续空格替换为单个|字符的方法

核心思路是用正则表达式匹配任意长度的连续空白(或仅空格),再替换为单个|字符。以下是不同场景下的实现方式:

命令行工具(sed)

终端处理文本可直接用sed的全局替换命令:

# 仅匹配空格(不包含制表符等其他空白)
echo "thing       thing2    thing3         thing4" | sed 's/  */|/g'

# 匹配所有空白字符(空格、制表符等)
echo "thing       thing2    thing3         thing4" | sed 's/[[:space:]]\+/|/g'

执行后输出:thing|thing2|thing3|thing4

Python 实现

使用re模块的sub函数完成正则替换:

import re

original_str = "thing       thing2    thing3         thing4"
# 替换所有连续空白为|
result = re.sub(r'\s+', '|', original_str)
# 若仅需替换空格,用 r' +' 替代 r'\s+'
# result = re.sub(r' +', '|', original_str)

print(result)

JavaScript 实现

通过字符串的replace方法结合正则全局匹配:

const originalStr = "thing       thing2    thing3         thing4";
// 全局替换所有连续空白为|
const result = originalStr.replace(/\s+/g, '|');
// 仅替换空格的话,用 / +/g
// const result = originalStr.replace(/ +/g, '|');

console.log(result);

PHP 实现

使用preg_replace函数完成正则替换:

$originalStr = "thing       thing2    thing3         thing4";
// 替换连续空白为|
$result = preg_replace('/\s+/', '|', $originalStr);
// 仅替换空格则用 '/ +/'
// $result = preg_replace('/ +/', '|', $originalStr);

echo $result;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:55:25