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.
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.
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 "".
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.
You can use \s.
For example:
presaleEstimateHigh = Regex.Replace(presaleEstimateHigh, @"[A-Za-z\s]", string.Empty);
Without regular expressions:
var chars = str.Where(c => !char.IsLetter(c) && !char.IsWhitespace(c)).ToArray();
var rest = new string(chars);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With