'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()?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serve Laurijssen |
