Viktorianec Viktorianec - 1 year ago 293
Objective-C Question

How delete all symbols from string except letters and numbers?

I am trying use next code:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\p{L}[0-9]]+|-" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];

but it doesn't work. I use different variations of this, but without success too.

Example text:

Это тестовый.!!?! ;$%#@@@## (вопрос) номер 1256 - верно.

Example output:

Это тестовый вопрос номер 1256 - верно

Answer Source

Your regex is actually matching characters you want to remove, but it is corrupt and does not even do that (due to a "wild" ]).

If you need to delete all chars except letters, digits, hyphens and whitespaces, use @"[^\\p{L}\\p{M}0-9\\s-]+".


  • [^\\p{L}\\p{M}0-9\\s-]+ - one or more characters that are NOT:
    • \\p{L} - Unicode letters
    • \\p{M} - diacritics
    • 0-9 - ASCII digits
    • \\s - whitespace
    • - - a literal hyphen.

See the online Objective-C demo:

NSString *text = @"Это тестовый.!!?! ;$%#@@@## (вопрос) номер 1256 - верно";
NSError *error = NULL;
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"[^\\p{L}\\p{M}0-9\\s-]+" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *result = [regexp stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@""];

Result: Это тестовый вопрос номер 1256 - верно

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download