Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove alpha characters and white space from string

Tags:

c#

.net

I have a string which contains many characters. I want to remove A-Za-z and white space and be left with the rest. What's the best way to do this?

Here's what I've tried

presaleEstimateHigh = Regex.Replace(presaleEstimateHigh, @"[A-Za-z]", string.Empty);

but I also need to remove white space.

like image 644
Sachin Kainth Avatar asked Nov 17 '12 19:11

Sachin Kainth


People also ask

How do I remove all alphanumeric characters from a string?

Method 1: Using ASCII values Since the alphanumeric characters lie in the ASCII value range of [65, 90] for uppercase alphabets, [97, 122] for lowercase alphabets, and [48, 57] for digits. Hence traverse the string character by character and fetch the ASCII value of each character.

How do you remove spaces from a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do I remove the alphabet from a string?

String str = "a12334tyz78x"; str = str. replaceAll("[^\\d]", ""); You can try this java code in a function by taking the input value and returning the replaced value as per your requirement.


2 Answers

You can use \s.

For example:

presaleEstimateHigh = Regex.Replace(presaleEstimateHigh, @"[A-Za-z\s]", string.Empty);
like image 178
Dan Avatar answered Oct 20 '22 17:10

Dan


Without regular expressions:

var chars = str.Where(c => !char.IsLetter(c) && !char.IsWhitespace(c)).ToArray();
var rest = new string(chars);
like image 44
tukaef Avatar answered Oct 20 '22 18:10

tukaef