Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all numbers from a string

I have a string that I need to remove all numerical values from. So for example

H1 --> H
Thi2341s i34s a876 57834tes9873t --> This is a test

And so forth...

I tried this method...

NSString *newString = [string stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@""];

... though it didn't successfully remove the numbers from the string. I am guessing that @"[^0-9]" isn't a valid occurrence. Any ideas of how I can achieve this without copying the method ten times for each digit?

like image 370
user2662669 Avatar asked Oct 27 '25 10:10

user2662669


1 Answers

You have to indicate that a regular expression search should be used:

NSString *newString = [string stringByReplacingOccurrencesOfString:@"[0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];

And note the regular expression needs to be [0-9], not [^0-9]. What you have says "any character except the digits 0-9".

like image 129
rmaddy Avatar answered Oct 28 '25 22:10

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!