Resolved Getting a mobile number from a user

WB1975

Well-known member
Joined
Apr 3, 2020
Messages
87
Programming Experience
Beginner
if i wanted a user to enter a mobile number in a console application
so the user can only input
011 086 087 to start and then 7 digits after that
so as in 0142223434

would it be best done with regular expressions? or is there a better way?
 
Last edited by a moderator:
Your first number contains non numeric values. Those spaces will need to be accounted for. Why would you need Regex?

Just get the count of the number of chars in the string. If the count exceeds the limit of the condition, tell them its not a valid mobile number.

The first number is missing a digit, and I'd actually prefer if you didn't post actual mobile numbers on the forum. As this is how people get spammed. ;)

I've replaced the network prefix numbers for you.
 
I suspect the OP is also trying to validate that the number is a valid mobile number by checking parts of the phone number to see if the following the phone number scheme. (For example in the US, the middle digit in the area code originally could only be 0,1, or 2 until they added a few other legal digits in the North American Numbering Plan.) In general, unless you know which country (or set of countries) you want to check, you'll need to become an expert in all the phone number schemes.
 
hi guys

yes wasnt thinking about tht mobile number, even though its not mine, apologies

i just want to be able to check the first three numbers are either
111
112
113 for example, and that the rest are all digits, and that its no less or no more than 10 digits long.
 
First you can remove irrelevant characters like space (and maybe dash, plus, paranthesis), I think Regex.Replace is easier to use for this than Replace or Remove methods of string.
Then a Regex.IsMatch with pattern @"1{2}[1-3]\d{7}" is also easier than the alternative, which would be looping and checking things like string.Length, string.StartsWith and char.IsDigit.

You could of course also loop the entire input and inspect each character, ignoring spaces and the like, and keep count of digits, but it would be more slightly more difficult checking pattern of specific digits at specific positions.
 
Screenshot_130.jpg


Thought we could have a little fun with this one. :cool:

This way doesn't use any regex or char.isdigit or parsing. I stuck to the object orientation approach, and check periodically what key was pressed, and if the key was between 0-9, a string builder builds up the values of the mobile number as each numeric key is detected and I later return the helper class to the calling codes method so you can reuse the string built value. Try it and see if you like it. It executes at 0.32ms and I assume a Regex version of this code would be somewhat slower.
C#:
    public class Helper
    {
        private static readonly StringBuilder NumberBuilder = new StringBuilder();
        public string Number_Builder
        {
            get => NumberBuilder.ToString();
            set => NumberBuilder.Append(value);
        }
    }
    public class Keys_Constructor
    {
        public string Console_Key(char key)
        {
            Helper helper = new Helper();
            if (key >= '0' && key <= '9')
            {
                helper.Number_Builder = (Convert.ToString(key));
            }
            /* Add an else condition for non numbers */
            return helper.Number_Builder.ToString();
        }
    }
    internal static class Program
    {
        internal static void Main()
        {
            Helper helper = Verify_Mobile_From_User();
            /* Do something with helper.Number_Builder */
        }
        private static Helper Verify_Mobile_From_User()
        {
            Console.Clear();
            Console.WriteLine("What is your mobile phone number?");
            Helper helper = new Helper();
            while (!Console.KeyAvailable && helper.Number_Builder != null && helper.Number_Builder.ToString().Length < 10)
            {
                Keys_Constructor keys_Constructor = new Keys_Constructor();
                keys_Constructor.Console_Key(Console.ReadKey(true).KeyChar);
                Console.SetCursorPosition(34, Console.CursorTop - 1);
                Console.WriteLine(helper.Number_Builder.ToString());
            }
            Console.WriteLine($"Mobile number verified : { helper.Number_Builder.ToString() }");
            return helper;
        }
    }
To get only the three digits for the network providers country code, you can call substring on the helpers string builder like this : string x = helper.Number_Builder.ToString().Substring(0, 3);

Hope this helps.
 
@Sheepings it is an interesting take, although not complete to requirements (vague as they are). I still prefer the 3 lines of regex code to somewhere around 50-60 lines. :coffee:
 
Thanks. 45 lines actually John.

But I'd like to see if you can do exactly what I've done with Regex and do it all within under 0.32ms. Do you dare to give it a go? :p

I could actually clean up a lot of my code, and probably get a bit more speed out of it. :)

although not complete to requirements (vague as they are)
Please explain?

It does what was asked. Does it not?
 
I will not be 45 lines when you "Add an else condition for non numbers" that at least let spaces slip through and does not verify other characters, and you need to verify first three numbers also.
 
Here's my three:
C#:
var input = "(+111) 2345-678"; // = Console.ReadLine()
input = Regex.Replace(input, "[() +-]", string.Empty);
var valid = Regex.IsMatch(input, @"1{2}[1-3]\d{7}");
Input example has more than spaces and digits, but I think it would be a common input pattern for phone numbers different places.
 
If you wanted to only allow valid input, a given prefix and 7 digits, you could do this:
C#:
var prefixes = new string[] { "111", "112", "113" };
for (var i = 0; i < prefixes.Length; i++)
{
    Console.WriteLine($"{i + 1}: {prefixes[i]}");
}
Console.Write("Choose a prefix: ");
var prefix = 0;
while (!(prefix >= 1 && prefix <= prefixes.Length))
{
    prefix = GetDigit();
}
Console.Write("\nInput 7 digits phone number (space and dash allowed): ");
var digits = new System.Text.StringBuilder();
while (digits.Length < 7)
{
    digits.Append(GetDigit());
}
Console.Write($"\nPhone number: ({prefixes[prefix - 1]}) {int.Parse(digits.ToString()):000 00 00}");
Console.ReadKey(true);
Along with helper method:
C#:
static int GetDigit()
{
    var input = new ConsoleKeyInfo();
    while (!char.IsDigit(input.KeyChar))
    {
        input = Console.ReadKey(true);
        //allow some formatting chars in input
        if ("- ".Contains(input.KeyChar))
        {
            Console.Write(input.KeyChar);
        }
    }
    Console.Write(input.KeyChar);
    return (int)char.GetNumericValue(input.KeyChar);
}
 
That's also an interesting take. But the overhead involved in calling Regex is not only costly, but as I've proven, its irrelevant. So if you're going to call Regex once, you may as well use Regex for everything else, and that includes checking if a char.isdigit and value.Contains(input.KeyChar) and char.GetNumericValue.

I think I'd stick to using my own method. As it doesn't require bringing regex into it, and it also allows for the number to be passed around in an object orientation sense. Not to mention it also has the upper-hand on speed and performance and lacks the additional overhead used when calling Regex for something that doesn't require it. I realize I said that part twice. :LOL:

will not be 45 lines when you "Add an else condition for non numbers" that at least let spaces slip through and does not verify other characters, and you need to verify first three numbers also.
Ok, here is your prefix :
C#:
        internal static void Main()
        {
            Helper helper = Verify_Mobile_From_User();
            string prefix = helper.Number_Builder.ToString().Substring(0, 3);
        }
Here is your white space :
C#:
        if (key >= '0' && key <= '9' || key == ' ')
The else condition is only a safeguard for reporting non numeric chars.

Edit, removed irrelevant inline comment.
 
Last edited:
Wow thanks so much guys will study this tomorrow, or maybe once you guys have sorted out what the best approach is lol
 
Regex is a heavy concept to call upon. It isn't necessary for what you are doing. The code I wrote - yes, there are 45 lines of code, compared to Johns 35 lines of code. Yet my method is twice as fast due to the large overhead involved in using Regex. And until Microsoft address this in the next release, then Regex would be something I'd consider because it will no longer be hampered by any such overheads, as the next microsoft release is said to address this very issue. But until that happens, I'd advice sticking with the non Regex version.

Btw, I am not a Regex hater, or anything like that. @Skydiver knows I am obsessed with Regex, and I use it often. But its not worth using for something as simple as what you're doing In my opinion. The choice is really up to you though. (y)
 
If you're referring to post 11 then there is no regex there. The 3 lines in post 10 has regex. The computing time no matter which approch you choose for such a trivial task would be milliseconds.
 
Back
Top Bottom