
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find and Extract a Number from a String in C#
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
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
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.
Advertisements