Shehroz Jalil Shehroz Jalil - 3 months ago 10
C# Question

how to make two chunks of a string having characters too using c#

4200 47 Street Alberta Beach, T0E 0A0 AB 780-544-0137


this is my string having character values as well, the last characters having - in them is a phone number i want to make two chunks so i can save phone number in different and the first alphanumeric thing in a different variable using c#. can anyone help me how to do this?
i have used regex for number and for string like

PhoneNumber = Regex.Replace(Addrs, "[^000-9--]+", string.Empty);


and for string i have used regex as well

Address = Regex.Replace(Addrs, @"[\d-]", string.Empty);


but
the problem is , the address contains characters as well and this regex will split only character into one and string into one chunk

Answer

You can use a regular expression. Use something like http://regexr.com/ to experiment.

Assuming the phone number is always as in the example provided and at the end of the string,

\d{3}-\d{3}-\d{4}$
  • \d{3} = exactly 3 digits
  • followed by dash
  • \d{3} = exactly 3 digits
  • followed by dash
  • \d{4} = exactly 4 digits
  • $ = end anchor

    string text = "4200 47 Street Alberta Beach, T0E 0A0 AB 780-544-0137";
    string pattern = @"\d{3}-\d{3}-\d{4}$"; 
    Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
    Match match = rgx.Match (text);
    if (match.Success) {
        string phoneNumber = match.Value;
        Console.WriteLine (phoneNumber); //780-544-0137
    }