How to find and extract a number from a string in C#?

CsharpServer Side ProgrammingProgramming

A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs.

Here are basic pattern metacharacters used by RegEx −

* = zero or more
? = zero or one
^ = not
[] = range

The ^ symbol is used to specify not condition.

the [] brackets if we are to give range values such as 0 - 9 or a-z or A-Z

Using Char.IsDigit()

Example

 Live Demo

using System;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         string str1 = "123string456";
         string str2 = string.Empty;
         int val = 0;
         Console.WriteLine($"String with number: {str1}");
         for (int i = 0; i < str1.Length; i++){
            if (Char.IsDigit(str1[i]))
               str2 += str1[i];
         }
         if (str2.Length > 0)
            val = int.Parse(str2);
            Console.WriteLine($"Extracted Number: {val}");
         Console.ReadLine();
      }
   }
}

Output

String with number: 123string456
Extracted Number: 123456

In the above example we are looping all the characters of the string str1. The Char.IsDigit() validates whether the particular character is a number or not and adds it to a new string which is later parsed to a numer.

Using Regex

Example

 Live Demo

using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         string str1 = "123string456";
         string str2 = string.Empty;
         int val = 0;
         Console.WriteLine($"String with number: {str1}");
         var matches = Regex.Matches(str1, @"\d+");
         foreach(var match in matches){
            str2 += match;
         }
         val = int.Parse(str2);
         Console.WriteLine($"Extracted Number: {val}");
         Console.ReadLine();
      }
   }
}

Output

String with number: 123string456
Extracted Number: 123456

In the above example, we use the regular expression (\d+) to extract only the numbers from the string str1.

raja
Published on 24-Sep-2020 10:57:23
Advertisements