如何使用C# Regexp删除字符串中XXX及其前一个单词?
Remove the Word Before "XXX" and "XXX" Itself Using C# Regex
Got it, let's tackle this problem with C# regex! The goal is to strip out the word immediately preceding "XXX" along with "XXX" itself from a string. Here's a straightforward approach with examples:
Basic Solution (Standard Words)
If your "words" are made up of letters, numbers, or underscores (standard word characters), use this regex pattern. It targets a full word, the whitespace between it and "XXX", and "XXX" itself, then replaces that entire match with nothing.
Code Example
using System; using System.Text.RegularExpressions; class RegexDemo { static void Main() { string inputString = "Quick brown XXX fox jumps over XXX lazy dog"; // Regex pattern breakdown: // \b: Word boundary (ensures we match a standalone word) // \w+: Matches one or more standard word characters // \s+: Matches one or more whitespace characters (spaces, tabs, etc.) // XXX: Exact match for the target string // \b: Ensures we don't partial-match strings like "XXX123" string regexPattern = @"\b\w+\s+XXX\b"; string result = Regex.Replace(inputString, regexPattern, string.Empty); Console.WriteLine(result); // Output: "Quick fox jumps over lazy dog" } }
Handling Non-Standard Words
If your words include special characters (like hyphens, apostrophes, or symbols), replace \w+ with \S+—this matches any sequence of non-whitespace characters, covering more complex "word" scenarios.
Code Example
string inputString = "Hello mother-in-law XXX test this-is-a-word XXX example"; string regexPattern = @"\b\S+\s+XXX\b"; string result = Regex.Replace(inputString, regexPattern, string.Empty); Console.WriteLine(result); // Output: "Hello test example"
Key Notes
- Word Boundaries (
\b): These prevent accidental partial matches. For example, they won't target "brown" in a string like "brownXXX fox" (since there's no whitespace or word boundary between them). - Whitespace Flexibility:
\s+handles multiple spaces or tabs between the word and "XXX"—no need to adjust for inconsistent spacing. - Edge Cases: If "XXX" appears at the start of the string (with no preceding word), the regex won't match anything, so "XXX" stays in place (which aligns with the requirement to only remove the word before "XXX" plus "XXX").
内容的提问来源于stack exchange,提问作者Vnuuk
相关产品推荐
相关产品推荐

