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

技术问询:如何移除指定字符,仅保留特定前缀后的该字符?

Solution for Conditional Character Removal

Hey there! Let's break down how to solve this problem. From your example, it seems you want to remove all instances of the > character, except when it immediately follows the specific string <test@gmail.com>. Regular expressions are ideal for this kind of conditional replacement, and here's how to implement it across common languages:

JavaScript Implementation

Since your sample code uses JavaScript, let's start with that:

var para = '<test@gmail.com> >Lorem ipsum dolor sit amet,<test@gmail.com> consectetur >adipiscing elit. Integer nec > >odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla >quis sem at nibh elementum imperdiet.Duis sagittis ipsum. Praesent >mauris. Fusce nec tellus...';

// Replace all > that are NOT preceded by <test@gmail.com>
var cleanedPara = para.replace(/(?<!<test@gmail.com>)>/g, '');

console.log(cleanedPara);

How This Works

The regex (?<!<test@gmail.com>)> uses a negative lookbehind assertion:

  • (?<!<test@gmail.com>) checks that the > is not immediately preceded by the string <test@gmail.com>
  • The g flag ensures we replace all matching instances across the entire string

After running this, the result will keep > only when it directly follows your target email string, and remove all other standalone > characters.

Python Implementation

If you're working in Python, the approach is nearly identical (Python 3.6+ supports lookbehind assertions):

import re

para = '<test@gmail.com> >Lorem ipsum dolor sit amet,<test@gmail.com> consectetur >adipiscing elit. Integer nec > >odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla >quis sem at nibh elementum imperdiet.Duis sagittis ipsum. Praesent >mauris. Fusce nec tellus...'

cleaned_para = re.sub(r'(?<!<test@gmail.com>)>', '', para)
print(cleaned_para)

Edge Case Note

If your requirement is to keep > even if there's whitespace between <test@gmail.com> and > (e.g., <test@gmail.com> >), you can adjust the regex to account for optional whitespace:

// For JavaScript (allow optional spaces before >)
para.replace(/(?<!<test@gmail.com>\s*)>/g, '');

This modified regex will preserve > even if there are spaces between your target string and the character.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:50:30