Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove numbers from string using Regex.Replace?

Tags:

c#

regex

I need to use Regex.Replace to remove all numbers and signs from a string.

Example input: 123- abcd33
Example output: abcd

like image 385
Gold Avatar asked Nov 01 '09 14:11

Gold


People also ask

How do I remove numbers from a string?

To remove all numbers from a string, call the replace() method, passing it a regular expression that matches all numbers as the first parameter and an empty string as the second. The replace method will return a new string that doesn't contain any numbers.

How to remove number from text in javascript?

Very close, try: questionText = questionText. replace(/[0-9]/g, '');

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.

How do I remove numbers from a string in Python?

In Python, an inbuilt function sub() is present in the regex module to delete numbers from the Python string. The sub() method replaces all the existences of the given order in the string using a replacement string.


2 Answers

Try the following:

var output = Regex.Replace(input, @"[\d-]", string.Empty); 

The \d identifier simply matches any digit character.

like image 198
Noldorin Avatar answered Sep 21 '22 06:09

Noldorin


You can do it with a LINQ like solution instead of a regular expression:

string input = "123- abcd33"; string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray()); 

A quick performance test shows that this is about five times faster than using a regular expression.

like image 20
Guffa Avatar answered Sep 18 '22 06:09

Guffa