Search code examples
c#stringwinformsintegerpoint-of-sale

How to check if there is a number and the letter X in a textbox in c#


I'm using C# and winforms. So I'm trying to build a POS app that has a textbox for barcodes and commands. One of the commands is "t" for total.

I want to implement another command that has a number and the letter "x" after it, for the quantity of the next item scanned or entered. Basically I want to make it so that if you put in "2x" into the textbox, it sets a variable to 2. Is there any easy way to that for any integer number. Like if(txtbarcode.text == int + "x") (I know this code doesn't work but it's here as an example)

Any help would be greatly appreciated, Thanks. EB.


Solution

  • Seems using regular expression can help in this case

    Here is the snippet

    using System;
    using System.Text.RegularExpressions;
                        
    public class Program
    {
        public static void Main()
        {
            var pattern = @"^(-?\d+\.?\d*)x$"; // support negatives and decimal
            var match = Regex.Match("123.31x", pattern);
            
            if(match.Success) {
                Console.WriteLine(match.Groups[1]); //return numbers only
            }
        }
    }
    

    supported cases

    123x
    -1x
    123.31x