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

正则表达式需求:移除XXX(忽略大小写)及其前任意符号组成的词

Solution to Remove Target Term and Its Preceding Word (Any Symbols Allowed)

Got it, let's tweak the regex to perfectly fit your requirement. The original pattern was too limited—it only matched word characters and slashes, and didn't account for case insensitivity. Here's the fixed approach:

Step 1: Updated Regular Expression

Use this pattern (with built-in case insensitivity):

@"\s*[\S]+\s+(?i)XXX"

Or alternatively, apply the ignore case flag explicitly when running the replacement:

@"\s*[\S]+\s+XXX"

paired with RegexOptions.IgnoreCase.

Step 2: Breakdown of the Regex

Let's walk through what each part does:

  • \s*: Matches 0 or more whitespace characters (handles any leading spaces before the preceding word)
  • [\S]+: Matches 1 or more non-whitespace characters—this is the critical fix! It captures any sequence of symbols, letters, numbers, or punctuation (like M.D,D/ in your example)
  • \s+: Matches 1 or more whitespace characters between the preceding word and the target term
  • (?i): Inline modifier that turns on case-insensitive matching, so XXX, xXx, Xxx, etc., all get caught

Step 3: Example Usage in C#

Here's how you'd implement this in code:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "This is KKK M.D,D/ xXx PPP";
        // Option 1: Using inline case-insensitive modifier
        string result1 = Regex.Replace(input, @"\s*[\S]+\s+(?i)XXX", "");
        // Option 2: Using RegexOptions.IgnoreCase
        string result2 = Regex.Replace(input, @"\s*[\S]+\s+XXX", "", RegexOptions.IgnoreCase);
        
        Console.WriteLine(result1); // Output: This is KKK PPP
        Console.WriteLine(result2); // Output: This is KKK PPP
    }
}

Why the Original Regex Failed

Your initial pattern @"\s*[\w/]+\s+XXX" had two key flaws:

  1. [\w/] only matches word characters (letters, numbers, underscores) and slashes—it couldn't handle punctuation like . or , in M.D,D/
  2. It didn't include case insensitivity, so xXx wouldn't be recognized as a match

This updated solution fixes both issues and works exactly as needed for your example input.

内容的提问来源于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:57:49