ZeMoon
ZeMoon

Reputation: 20274

C# Trim end of string by pattern

I want to trim the end of a series of strings to remove a suffix which follows a pattern.

In the following examples, I want to trim the Vx suffix at the end.

The numerical part could be any number of digits.

Example strings

AbcV1
BcdV12
TuvV32
VwxV42

Output

Abc
Bcd
Tuv
Vwx

How could I implement such a logic in C#? Is there a regex/pattern based way to use .TrimEnd()?

Upvotes: 1

Views: 498

Answers (1)

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

So you want any V with digits after that removed. This would do it.

public static void Main()
{
   string[] arr = { "AbcV1", "BcdV12", "TuvV32", "VwxV42" };
    
    foreach (string a in arr)
      Console.WriteLine(System.Text.RegularExpressions.Regex.Replace(a, "V[0-9]+$", ""));
    
}

or

"V[\d]+$"

whatever you prefer.

Upvotes: 4

Related Questions