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

CsharpProgrammingServer Side Programming

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
raja
Published on 20-Aug-2018 12:51:15
Advertisements