daspianist
daspianist

Reputation: 5525

Using stringByReplacingOccurrencesOfString to take into consideration "words"

My goal is to use stringByReplacingOccurrencesOfString to replace occurrences of words or phrases with replacements. The words and their replacements are found in a dictionary such as that the word or phrases are keys, and their values are their replacements:

{"is fun" : "foo",
 "funny" : "bar"}

Because stringByReplacingOccurrencesOfString is literal and disregards "words" in the convention Western language sense, I am running in the trouble where the following sentence:

"He is funny and is fun",

the phrase "is fun" is actually detected twice using this method: first as part of "is funny", and the second as part of "is fun", causing an issue where a literal occurrence is used for word replacement, and not realizing that it is actually part of another word.

I was wondering if there is a way to use stringByReplacingOccurrencesOfString that takes into consideration of wording, and so a phrase like "is funny" can be viewed in its complete self, and not also be viewed as "is funny" where "is fun" detected.

By the way, this is the code I am using for replacement when iterating across all the keys in the dictionary:

NSString *newText = [wholeSentence stringByReplacingOccurrencesOfString:wordKey withString:wordValue options:NSLiteralSearch range:[wholeSentence rangeOfString:stringByReplacingOccurrencesOfString:wordKey]];
        iteratedTranslatedText = newText;

Edit 1: Using the suggested solutions, this is what I have done:

NSString *string = @"Harry is fun. Shilp is his fun pet dog";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\bis fun\b" options:0 error:nil];
if (regex != nil) {
    NSTextCheckingResult *firstMatch = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
    //firstMatch is returning null
    if (firstMatch) {
        NSRange resultRange = [firstMatch rangeAtIndex:0];
        NSLog(@"first match at index:%lu", (unsigned long)resultRange.location);

    }
}

However, this is returning firstMatch as null. According to the regex tutorial on word boundaries, this is how to anchor a word or phrase, so I am unsure why its not returning anything. Help is appreciated!

Upvotes: 1

Views: 497

Answers (1)

Pandara
Pandara

Reputation: 139

As your comment, you can use NSRegrlarEXPression in your project. For example:

NSString *string = @"He is funny and is fun";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"is fun([^a-zA-Z]+|$)" options:0 error:nil];
if (regex != nil) {
    NSTextCheckingResult *firstMatch = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
    if (firstMatch) {
        NSRange resultRange = [firstMatch rangeAtIndex:0];
        NSLog(@"first match at index:%d", resultRange.location);
    }
}

And to result: first match at index:16

Upvotes: 1

Related Questions