I'm pretty new to using regex
in iOS
, and I'm experimenting with it. I'm struggling to find a solution to the problem I have. I apologize in advance if this has been answered before or I'm just missing something really obvious and/or using the wrong tool to accomplish my goal.
I have a string that the user will enter in a textfield
. How do I then change that to correct a spelling of a word that is contained inside the string?
NSString *userstring = @"Jon Travalta";
NSError *error = NULL;
NSString *modstring = @"";
NSRegularExpression *regex = [[NSRegularExpression alloc]init];
regex = [NSRegularExpression regularExpressionWithPattern:@"(Jon|Johnathan|Jonathen|John)\\s(Travalta|Travalte|Travelta|Travolta)" options:NSRegularExpressionCaseInsensitive error:&error];
modstring = [regex stringByReplacingMatchesInString:userstring options:0 range:NSMakeRange(0,[userstring length]) withTemplate:@"John Travolta"];
That works and corrects the string fine, but let's say the string is something else. I want to keep that regex active to check the string if it contains any of those elements to correct it.
So let's say the string is set, before the above check, to "Anthony Hopkin". I would then also use another regexwithpattern
to check the string to correct that one with the correct spelling of the name.
regex = [NSRegularExpression regularExpressionWithPattern:@"(Anthony|Antony|Tony|)\\s(Hopkin|Hapkin|Hopkins)" options:NSRegularExpressionCaseInsensitive error:&error];
modstring = [regex stringByReplacingMatchesInString:userstring options:0 range:NSMakeRange(0,[userstring length]) withTemplate:@"Anthony Hopkins"];
This will replace the string with Anthony Hopkins, even if it's the first string.
If I do a different alloc of NSRegularExpression
and different stringByReplacingMatchesInString
, it just doesn't do anything and the string stays what it was to begin with.