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

技术问询:如何编写正则表达式匹配除@开头子串外的所有内容

正则表达式实现:匹配所有字符并排除以@开头的子串

核心思路

要实现需求,我们需要匹配并移除所有以@开头、直到下一个空白字符(或字符串结尾)的子串,保留其余所有正常字符。

正则表达式

@\S+
  • @:精准匹配@符号起始位
  • \S+:匹配一个或多个非空白字符,覆盖从@开始到下一个空格前的全部内容(包括字母、数字、特殊符号)

代码示例

Python 实现

import re

input_text = "this is the @example te@s5t @abc17$ ++ 123"
# 移除所有@开头的子串
cleaned_text = re.sub(r'@\S+', '', input_text)
# 清理多余空格(可选,优化输出格式)
cleaned_text = re.sub(r'\s+', ' ', cleaned_text).strip()

print(cleaned_text)  # 输出: this is the te ++ 123

JavaScript 实现

const inputText = "this is the @example te@s5t @abc17$ ++ 123";
let cleanedText = inputText.replace(/@\S+/g, '');
// 清理多余空格
cleanedText = cleanedText.replace(/\s+/g, ' ').trim();

console.log(cleanedText); // 输出: this is the te ++ 123

说明

  • 替换后可能出现连续空格,用\s+替换为单个空格并去除首尾空格,能让最终结果更规整;
  • 该正则适用于绝大多数常见场景,可直接适配支持正则替换的编程语言。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:05:19