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

如何编写正则表达式清理表单输入中的无效空格?

多场景无效空格清理的正则实现方案

针对你需要的四种空格处理规则,结合给定的测试用例,我们可以通过分步正则替换来实现,每一步对应一个需求点,逻辑清晰且容易验证:

处理步骤说明

  1. 统一换行符格式:先将\r\n替换为\n,避免混合换行符带来的处理混乱。
  2. 转换制表符为空格:根据测试用例预期,制表符最终需要转为空格并参与多空格合并。
  3. 清理换行符前后空格:去掉\n前后所有连续空格,只保留换行符本身。
  4. 合并连续多空格:把字符串内两个及以上的连续空格缩减为一个。
  5. 移除首尾空格:清除字符串开头和结尾的所有空格,空字符串直接返回空。

Rust 实现代码

use regex::Regex;

fn not_useful_space(s: &str) -> String {
    let mut result = s.replace("\r\n", "\n");
    // 把制表符转换为空格
    result = result.replace('\t', " ");
    // 清理换行符前后的所有空格
    result = Regex::new(r"\s*\n\s*").unwrap().replace_all(&result, "\n").to_string();
    // 合并连续多空格为单个空格
    result = Regex::new(r"\s{2,}").unwrap().replace_all(&result, " ").to_string();
    // 移除首尾空格
    result.trim().to_string()
}

// 测试用例验证
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_space_cleanup() {
        assert_eq!(not_useful_space("   "), "");
        assert_eq!(not_useful_space("    a l    l   lower      "), "a l l lower");
        assert_eq!(not_useful_space("    i need\n new lines\n\n many times     "), "i need\nnew lines\n\nmany times");
        assert_eq!(not_useful_space("    i need  \n new lines \n\n many times     "), "i need\nnew lines\n\nmany times");
        assert_eq!(not_useful_space("  i need \r\n new lines\r\nmany times   "), "i need\nnew lines\nmany times");
        assert_eq!(not_useful_space("    i need \t new lines\t \t many times     "), "i need new lines many times");
        assert_eq!(not_useful_space("  à   la  "), "à la");
    }
}

各步骤正则解释

  • "\r\n":直接匹配Windows风格换行符,替换为Unix风格换行符,无需正则。
  • r"\s*\n\s*":\s*匹配任意数量的空格(包括0个),捕获\n前后的所有空格,替换后只保留\n。
  • r"\s{2,}":\s{2,}匹配两个及以上的连续空格,替换为单个空格。
  • trim():Rust内置方法,直接移除字符串首尾的所有空白字符(提前处理制表符后,这里主要处理首尾空格)。

原正则失效原因

你尝试的+|\\n +|\t +\\r\n .+存在几个核心问题:

  1. 第一个+缺少匹配目标,应为\s+才能匹配多空格,但仍无法覆盖全场景。
  2. 仅处理了\n和\t后面的空格,未处理前面的空格。
  3. 未包含\r\n转\n、首尾空格清理、多空格合并的逻辑。
  4. 正则逻辑混乱,\\r\n .+会匹配\r\n加任意字符,完全不符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:25:16