技术问询:如何移除指定字符,仅保留特定前缀后的该字符?
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
gflag 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

