如何在C#中使用Regex移除字符串中的指定子串?
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. So140702|142110tells the regex engine to look for either140702or142110in the input string. Regex.Replacescans 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
ABCand 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

