- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to write Regex for numbers only 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
Example
class Program{ public static void Main(){ string num = "123dh"; Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$"); var res = regex.IsMatch(num); System.Console.WriteLine(res); } }
Output
False
Example
class Program{ public static void Main(){ string num = "123"; Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$"); var res = regex.IsMatch(num); System.Console.WriteLine(res); } }
Output
True
Example
class Program{ public static void Main(){ string num = "123.67"; Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$"); var res = regex.IsMatch(num); System.Console.WriteLine(res); } }
Output
True
Advertisements