tags:

views:

227

answers:

2

I need to trim the first n alpha characters from a string.

Examples:

a123456 -> 123456
abc123456 -> 123456
abc123456def -> 123456def

Thanks in advance for any help.

+2  A: 

Try something like this:

String output = Regex.Replace(input, @"^[^\d]+", String.Empty);

Here is how the regular expression works:

^[^\d]+

^ anchors the expression to the beginning of the string
[^\d] is a character set matching all non-integral values
+ qualifies [^\d] by making it match one or more times

So basically this regular expression matches all non-integral characters in a string up until an integral character is found.

Andrew Hare
Spot on, thanks.
A: 
static string AlphaTrimRight(string value)
{
    while (!Char.IsNumber(value[0]))
        value = value.Substring(1, value.Length - 1);
    return value;
}
Shimmy
Does Substring share the underlying char[] with the original string?
Michael Myers
what do you mean?
Shimmy
Possibly nothing; C# strings might be implemented completely differently from Java strings. Java strings have an internal char[], which can be shared with strings created by the substring() method. I was just wondering if C# strings do the same thing. If they don't, this method looks like it will be rather inefficient (a lot of char[] copying).
Michael Myers
Apparently, C# strings cannot share the underlying data: http://stackoverflow.com/questions/1003915/sharing-character-buffer-between-c-strings-objects . Therefore, I don't like all the .Substring's you call in a loop.
Michael Myers
in C#, a string can be used as char[], example:char a = "asdf"[0];
Shimmy