Carnal
Carnal

Reputation: 22064

iOS - NSString regex match

I have a string for example:

NSString *str = @"Strängnäs"

Then I use a method for replace scandinavian letters with *, so it would be:

NSString *strReplaced = @"Str*ngn*s"

I need a function to match str with strReplaced. In other words, the * should be treated as any character ( * should match with any character).

How can I achieve this?

Strängnäs should be equal to Str*ngn*s

EDIT:

Maybe I wasn't clear enough. I want * to be treated as any character. So when doing [@"Strängnäs" isEqualToString:@"Str*ngn*s"] it should return YES

Upvotes: 3

Views: 1494

Answers (3)

Amen Jlili
Amen Jlili

Reputation: 1934

I think the following regex pattern will match all non-ASCII text considering that Scandinavian letters are not ASCII:

[^ -~]

Treat each line separately to avoid matching the newline character and replace the matches with *.

Demo: https://regex101.com/r/dI6zN5/1

Edit:

Here's an optimized pattern based on the above one:

[^\000-~]

Demo: https://regex101.com/r/lO0bE9/1

Edit 1: As per your comment, you need a UDF (User defined function) that:

  • takes in the Scandinavian string
  • converts all of its Scandinavian letters to *
  • takes in the string with the asterisks
  • compares the two strings
  • return True if the two strings match, else false.

You can then use the UDF like CompareString(ScanStr,AsteriskStr).

Upvotes: 3

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

I have created a code example using the regex posted by JLILI Amen

Code

NSString *string = @"Strängnäs";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^ -~]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"*"];
NSLog(@"%@", modifiedString);

Output

Str*ngn*s

Upvotes: 2

CRD
CRD

Reputation: 53000

Not sure exactly what you are after, but maybe this will help.

The regular expression pattern which matches anything is. (dot), so you can create a pattern from your strReplaced by replacing the *'s with .'s:

NSString *pattern = [strReplaced stringByReplacingOccurencesOfString:@"*" withString:"."];

Now using NSRegularExpression you can construct a regular expression from pattern and then see if str matches it - see the documentation for the required methods.

Upvotes: 0

Related Questions