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

如何在C#中使用Regex移除字符串中的指定子串?

Solution to Remove Specific Substrings with Regex in C#

Got it, let's figure out how to strip those two specific substrings from your string using C# regex. It's straightforward once you know the right pattern to use.

Approach 1: Match the Exact Substrings

Since you know the exact values you want to remove (140702 and 142110), the simplest regex pattern will target these two strings directly. We'll use Regex.Replace to swap any matches with an empty string.

Here's the full code example:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string input = "000603ABC140702-005051-I-FILL200-NNYYNY180319-142110-A2002.zip";
        // Regex pattern to match either of the two substrings
        string pattern = @"140702|142110";
        string result = Regex.Replace(input, pattern, string.Empty);
        
        Console.WriteLine(result);
        // Output: 000603ABC-005051-I-FILL200-NNYYNY180319--A2002.zip
    }
}

Breakdown of the Pattern

  • The | character in regex acts like an "OR" operator. So 140702|142110 tells the regex engine to look for either 140702 or 142110 in the input string.
  • Regex.Replace scans the entire input and replaces every occurrence of the matched patterns with an empty string, effectively removing them.

Bonus: Pattern for Dynamic Matches (If Needed)

If you ever need to remove similar substrings based on their position (not just exact values), you can adjust the regex to target their context:

  • To remove the 6-digit number right after ABC and before -, use (?<=ABC)\d{6}(?=-)
  • To remove the 6-digit number between two - characters, use (?<=-)\d{6}(?=-)

Combine them for a more flexible pattern:

string dynamicPattern = @"(?<=ABC)\d{6}(?=-)|(?<=-)\d{6}(?=-)";
string dynamicResult = Regex.Replace(input, dynamicPattern, string.Empty);

This would work even if the 6-digit values change, as long as they're in those specific positions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:41:29