如何将字符串中任意长度的连续空格替换为单个指定字符?
实现连续空格替换为单个|字符的方法
核心思路是用正则表达式匹配任意长度的连续空白(或仅空格),再替换为单个|字符。以下是不同场景下的实现方式:
命令行工具(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
相关产品推荐
相关产品推荐

