Andrew
Andrew

Reputation: 7788

Trim number function

I need to trim the last portion of the string that contains the number. In addition, I need to trim the part which does not start with the zero

This is what I am doing and I did not include the 0 since I am not sure how should I ignore it if the numbers starts with the zero.

        textBox13.Text = "A14C0681414010";
        //textBox13.Text = "A14C1381414010"; numbers will vary
        var first = textBox13.Text.TrimEnd("123456789".ToCharArray());
        var last = textBox13.Text.Substring(first.Length);
        // part 1 should contain A14C0
        // part 2 should contain 681414010

How can I achieve it? My function does not do it

Upvotes: 0

Views: 1970

Answers (2)

Steve
Steve

Reputation: 8511

If there will always be a zero at the point you want to break you can find the position of that using string.IndexOf(). You can then break the string in to 2 substrings using that index.

Upvotes: 0

Heinzi
Heinzi

Reputation: 172330

Let's go through the regular expression step by step:

  • start with a digit, but not zero: [1-9]
  • followed by an arbitrary number of digits (including zero): [0-9]* (or abbreviated: \d*)
  • followed by "the end of the line" (to get only the "last portion"): $.

    var input = "A14C0681414010"; 
    foreach (Match m in Regex.Matches(input, "[1-9][0-9]*$")) {
        Console.WriteLine("Found: " + m.Value);
    }
    
    // Outputs "Found: 681414010"
    

Upvotes: 5

Related Questions