---
title: "Valid Phone number"  
description: "Valid Phone number"  
author: "Steilla Mitchel"  
published: 2024-06-12  
updated: 2024-06-12  
canonical: https://www.mindstick.com/forum/160728/valid-phone-number  
category: "c#"  
tags: ["c#", "programming language", "programming help", "programs"]  
reading_time: 2 minutes  

---

# Valid Phone number

Given a [text file](https://www.mindstick.com/forum/12828/converting-a-text-file-to-an-array-in-java) `file.txt` that contains a list of [phone](https://www.mindstick.com/articles/23411/the-most-effective-method-to-find-the-perfect-small-business-phone-system-for-your-business) numbers (one per line), write a one-liner bash [script](https://www.mindstick.com/interview/477/how-can-i-execute-a-php-script-using-command-line) to [print](https://www.mindstick.com/blog/301752/types-of-3d-printing-technology) all valid phone numbers.

You may assume that a valid phone number [must](https://www.mindstick.com/articles/12978/top-reasons-why-every-magento-ecommerce-store-must-opt-for-mobile-app) appear in one of the following two [formats](https://www.mindstick.com/forum/160705/explain-the-concept-of-datetime-formats-in-c-sharp): (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)

You may also assume each line in the text file must not contain [leading](https://answers.mindstick.com/qa/100394/5-iitians-who-made-india-proud-by-leading-the-world-s-biggest-companies) or [trailing](https://answers.mindstick.com/qa/105012/what-is-a-trailing-stop) white spaces.

## Replies

### Reply by Ravi Vishwakarma

Let's write code to **validate** the phone number in a specific format using **regex** in C#.

```cs
// Method to validate the phone number
        public static bool IsValidPhoneNumber(string PhoneNumber)
        {
            // Check if the input string is null or empty
            if (string.IsNullOrEmpty(PhoneNumber))
            {
                // Return false if the phone number is null or empty
                return false;
            }

            // Define the regex pattern to match valid phone numbers in the formats
            // (222) 222-2222 and 222-222-2222
            string pattern = @"^\(?\d{3}\)?[- ]?\d{3}[-]\d{4}$";

            // Use Regex.IsMatch to check if the phone number matches the pattern
            // RegexOptions.Multiline is used to ensure the pattern is applied to each line if the input contains multiple lines
            return Regex.IsMatch(PhoneNumber, pattern, RegexOptions.Multiline);
        }
```

Explanation:

- `^` asserts the position at the start of the string.
- `\(?` optionally matches an opening parenthesis `(`.
- `\d{3}` matches exactly three digits.
- `\)?` optionally matches a closing parenthesis `)`.
- `[- ]?` optionally matches a hyphen `-` or a space .
- `\d{3}` matches exactly three digits.
- `[-]` matches exactly a hyphen `-`.
- `\d{4}` matches exactly four digits.
- `$` asserts the position at the end of the string.

Now call this function

```cs
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
    public class Program
    {
        public static void Main()
        {
            IList<string> list = new List<string>
            {
                "(222) 222-2222",
                "222-222-2222",
                "124-125-4585",
                "996 748 8596",
                "7485965874",
                "(222) 222-2222", "222-222-2222", "123 456 7890", "222.222.2222"
            };

			foreach (var item in list)
            {
                bool IsMatch = Program.IsValidPhoneNumber(item);

                Console.BackgroundColor = IsMatch ? ConsoleColor.DarkGreen : ConsoleColor.Red;

                Console.WriteLine(item + " " + IsMatch);
                Console.ResetColor();
            }

            Console.ReadLine();
        }
	}
}
```

## Output :

![Valid Phone number](https://www.mindstick.com/mindstickforums/71df408b-c7cf-4571-adcb-addff22ff32e/images/8c105fd0-da1d-4e69-a751-d40ea8ca8823.png)


---

Original Source: https://www.mindstick.com/forum/160728/valid-phone-number

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
