
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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
- Related Articles
- REGEX in MySQL to display only numbers separated by hyphen.
- JavaScript regex program to display name to be only numbers, letters and underscore.
- Write a number array and using for loop add only even numbers in javascript?
- Write a number array and add only odd numbers?
- How to escape all special characters for regex in Python?
- How to write 5000 in Roman Numbers?
- How to restrict UITextField to take only numbers in Swift?
- JavaScript Regex to remove leading zeroes from numbers?
- How to Apply Data Validation to Allow Only Numbers in Excel?
- How to Only Allow Numbers in a Text Box using jQuery?
- Check if a string contains only alphabets in Java using Regex
- Python Program to check if String contains only Defined Characters using Regex
- How to use $regex in MongoDB?
- Regular expression to match numbers only in JavaScript?
- Finding only strings beginning with a number using MySQL Regex?

Advertisements