Simple get string (ignore numbers at end) in C#
Asked Answered
G

4

4

I figure regex is overkill also it takes me some time to write some code (i guess i should learn now that i know some regex).

Whats the simplest way to separate the string in an alphanumeric string? It will always be LLLLDDDDD. I only want the letters(l's), typically its only 1 or 2 letters.

Grits answered 27/9, 2009 at 19:2 Comment(1)
I resisted learning regexes for many years. Don't be me.Hardecanute
D
11

TrimEnd:

string result = input.TrimEnd(new char[]{'0','1','2','3','4','5','6','7','8','9'});
// I'm sure using LINQ and Range can simplify that.
// also note that a string like "abc123def456" would result in "abc123def"

But a RegEx is also simple:

string result = Regex.Match(input,@"^[^\d]+").Value;
Dipper answered 27/9, 2009 at 19:8 Comment(2)
Not all Regexes have to be complicated. In fact, some of the more complex ones can sometimes be better replaced with a traditional code construct. Knowing only a few concepts (Character Classes, Backtracking, Named Groups) is good enough to efficiently solve a lot of the everyday string handling issues - definitely worth learning the basics!Dipper
The RegEx solution doesn't work. For the input: asfsdf23424Aasdfsf222 it will output asfsdf. It sould be asfsdf23424AasdfsfBromine
S
10

I prefer Michael Stum's regex answer, but here's a LINQ approach as well:

string input = "ABCD1234";
string result = new string(input.TakeWhile(c => Char.IsLetter(c)).ToArray());
Subdeacon answered 27/9, 2009 at 19:23 Comment(1)
Very nice answer. But didn't cover all the bases: It starts at the beginning, only deems letter chars valid, and stops at the first invalid occurrence which would fail (depending on your requirements) for something like input = "ABCD1234EFGH5678"Kroll
S
3

You can use a regular expression that matches the digits to remove them:

input = Regex.Replace(input, "\d+$", String.Empty);

The old fashioned loop isn't bad either, it should actually be the fastest solution:

int len = input.Length;
while (input[len-1] >= '0' && input[len-1] <= '9') len--;
input = input.Substring(0, len);
Swedish answered 27/9, 2009 at 19:31 Comment(1)
That ^ should be a $ - otherwise you are matching numbers before the start of the string ;)Pachydermatous
P
0

They've got it - note the good solutions use the not operator to employ your problem description: "Not numbers" if you had the numbers at the front seems from my limited gains that you have to have what is called capturing groups to get past whatever it is on the front-end of the string. The design paradigm I use now is not delimiter character, followed by delimiter character, followed by an opening brace.

That results in needing a delimiter character that is not in the result set, which for one thing can be well established ascii values for data-delimitersl eg 0x0019 / 0x0018 and so on.

Pilotage answered 27/9, 2009 at 19:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.