Using stringByReplacingOccurrencesOfString to take into consideration "words" - ios

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!

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

Related

iOS NSRegularExpression how to find the first matching "TAIL" of pattern like: HEAD(.*)TAIL

For example:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"hello: (.*)ABC" options:0 error:NULL];
NSString *str = #"hello: bobABC123ABC";
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
NSLog(#"macthing part is %#", [str substringWithRange:[match rangeAtIndex:0]]);
The result of matching is "bobABC123ABC", so the matching of "ABC" in NSRegularExpression is finding the last "ABC" in the string instead of first.
I want the matching to be "bob",any one know how to achieve this?
Make you regular expression non-greedy. Say:
#"hello: (.*?)ABC"
^
|==> note this
instead of
#"hello: (.*)ABC"
From the documentation:
*? Match 0 or more times. Match as few times as possible.

RegEx - Detect specific strings before anything that isn't those strings [duplicate]

I have an NSString, let's say "H,L,K,P" how can I detect a specific character than then a wild-car character... for example, checking for ",*" would return ",L" ",K" and ",P" because they all have the specific "," and then they all have a character after them. Then I want to replace that string with itself plus a "period" appended to it.
So "H,L,K,P" would become "H,L.,K.,P."
Use a regular expression. The search pattern would be:
,(.)
the replacement pattern would be:
,$1.
Sample code:
NSString *string = #"H,L,K,P";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#",(.)"
options:0
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#",$1."];

NSMutableString replaceOccurrencesOfString replacing whole words

Is there a way to use replaceOccurrencesOfString (from NSMutableString) to replace whole words?
For example, if I want to replace all occurrences of a fraction in a string, like "1/2", I'd like that to match only that specific fraction. So if I had "11/2", I would not want that to match my "1/2" rule.
I've been trying to look for answers to this already, but I am having no luck.
You could use word boundaries \b with Regex. This example matches the "1/2" at the start and the end of the example string, but neither of the middle options
// Create your expression
NSString *string = #"1/2 of the 11/2 objects were 1/2ed in (1/2)";
NSError *error = nil;
NSRegularExpression *regex =
[NSRegularExpression
regularExpressionWithPattern:#"\\b1/2\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
// Replace the matches
NSString *modifiedString =
[regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"HALF USED TO BE HERE"];

Replace characters (unique then wildcard value) in a string with other characters

I have an NSString, let's say "H,L,K,P" how can I detect a specific character than then a wild-car character... for example, checking for ",*" would return ",L" ",K" and ",P" because they all have the specific "," and then they all have a character after them. Then I want to replace that string with itself plus a "period" appended to it.
So "H,L,K,P" would become "H,L.,K.,P."
Use a regular expression. The search pattern would be:
,(.)
the replacement pattern would be:
,$1.
Sample code:
NSString *string = #"H,L,K,P";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#",(.)"
options:0
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#",$1."];

Replace occurences of string that contains any number

Say I have a string that contains a control code "\f3" (yes it is RTF). I want to replace that control code with another string. At the moment I am using [mutableString replaceOccurrencesOfString:#"\f3" withString:#"replacement string" options:0 range:NSMakeRange(0, [mutableString length])];
This works fine, however sometimes the code can be "\f4" or even "\f12" for example. How do I replace these strings? I could use replaceOccurrencesOfString for each, but the better way to do it is using wildcards, as it could be any number.
Regular expressions would do it.
Take a look at NSRegularExpression (iOS >= 4) and this page for how regular expressions work.
You will want something like:
// Create your expression
NSError *error = nil;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:#"\\b\f[0-9]*\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
// Replace the matches
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"replacement string"];
WARNING : I've not tested my regaular expression and I'm not that great at getting them right first time; I just know that regular expressions are the way forward for you and it has to look something like that ;)

Resources