简体   繁体   中英

Find words with regEx and then add whitespaces inbetween with Objective-c

I was wondering how to add whitespaces inbetween letters/numbers in a string with Objective-C.

I have the sample code kinda working at the moment. Basically I want to turn "West4thStreet" into "West 4th Street".

NSString *myText2 = @"West4thStreet"; 
NSString *regexString2 = @"([a-z.-][^a-z .-])"; 

for(NSString *match2 in [myText2 componentsMatchedByRegex:regexString2 capture:1L]) { 

    NSString *myString = [myText2 stringByReplacingOccurrencesOfString:match2 withString:@" "]; 
    NSLog(@"Prints out: %@",myString); // Prints out: Wes thStreet // Prints out: West4t treet   

}

So in this example, it's replacing what I found in regEx (the "t4" and "hS") with spaces. But I just want to add a space inbetween the letters to separate out the words.

Thanks!

If you wrap parts of your regex patterns in parentheses, you can refer to them as $1, $2, etc in your replacement string (patterns are numbered from left to right, by the order of their opening parenthesis).

NSString *origString = @"West4thStreet";
NSString *newString = [origString stringByReplacingOccurrencesOfRegex:@"(4th)" withString:@" $1 "];

Not sure I understand your broader use case, but that should at least get you going...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM