How to find a number in a string in C#?


To find a number in a string, use Regular Expressions.

We have set the Regex pattern to get number from a string.

Regex r = new Regex(@"\d+");

Now, use Match class in C# to set the string.

Match m = r.Match("Welcome! We are open 365 days in a year!");

Use the Success property now to display the result if number is found in the string as shown in the following complete code −

Example

 Live Demo

using System;
using System.Text.RegularExpressions;

class Demo {
   static void Main() {

      Regex r = new Regex(@"\d+");
      Match m = r.Match("Welcome! We are open 365 days in a year!");

      if (m.Success) {
         Console.Write("Number: ");
         Console.WriteLine(m.Value);
      }
   }
}

Output

Number: 365

Updated on: 22-Jun-2020

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements