简体   繁体   中英

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

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) .

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

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.

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