Search code examples
c#regexstringsplitsubstring

Split string before any first number


string test = " Puerto Rico 123 " ;

I would like to obtain only "Puerto Rico". The idea is that instead of 123 it can be any number. How can I achieve this?


Solution

  • I suggest using regular expressions which is quite easy in the context: get all the non-digit [^0-9]* characters from the beginning ^ of the string:

    string test = " Puerto Rico 123 ";
    
    string result = Regex.Match(test, @"^[^0-9]*").Value;
    

    Linq is an alrernative:

    string result = string.Concat(test.TakeWhile(c => c < '0' || c > '9'));
    

    In case you want to trim the leading and trailing spaces (and have "Puerto Rico" as the answer, not " Puerto Rico "), just add .Trim(), e.g.:

    string result = Regex.Match(test, @"^[^0-9]*").Value.Trim();