从NSString中删除一些特殊字符,以获取附加到电子邮件的文件名PDF

问题描述 投票:0回答:1

我正在使用MFMailComposeViewController处理电子邮件中的附件,而pdf的文件名基于用户对事件名称的输入,因此这可能是John Wedding,或John's Wedding。

我想从文件名中删除任何特殊字符。

在我的代码中,我做到了这一点:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"'#%^&{}[]~|\/?.<," options:0 error:NULL];
NSString *string = self.occasion.title;
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];

NSString *fileName = [NSString stringWithFormat:@"(%@).pdf", modifiedString];

有了它,如果它是John的婚礼,它会从我的文件名中删除撇号,但是如果我有哈希或其中任何其他符号,它就不会删除文件名中的那些符号。

我在网上看过一些堆栈溢出示例,但它们看起来都非常复杂;我确切地知道我想从文件名中删除哪些符号。

任何指导都会非常感激。

ios regex nsstring mfmailcomposeviewcontroller
1个回答
2
投票
NSString *textString = @"abcd334%$^%^%80)(*^ujikl";

//this is for remove the specified characters
NSCharacterSet *chs = [NSCharacterSet characterSetWithCharactersInString:@"'#%^&{}[]/~|\?.<,"];
NSString *resultString = [[textString componentsSeparatedByCharactersInSet:chs] componentsJoinedByString:@""];

//this is for get the specified characters
NSCharacterSet *chs1 = [[NSCharacterSet characterSetWithCharactersInString:@"'#%^&{}[]/~|\?.<,"] invertedSet];
NSString *resultString1 = [[textString componentsSeparatedByCharactersInSet:chs1] componentsJoinedByString:@""];
NSLog(@"tex : %@",resultString);
NSLog(@"reverse string : %@",resultString1);

出局:

文字:abcd334 $ 80)(* ujikl

反向字符串:%^%^%^

© www.soinside.com 2019 - 2024. All rights reserved.