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

如何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:58:36