2

Pretty straightforward question:

Is there an Objective-C equivalent that iOS developers can use with NSString objects to do the same thing as Java's replaceAll("\p{Cntrl}", "") call on a String?

We already have this in Java:

String noControlCharsString = maybeHasControlCharsString.replaceAll("\\p{Cntrl}", "");

I want something like this in Objective-C too:

NSString *noControlCharsString = [maybeHasControlCharsString stringByReplacingControlCharsWithString:@""];

Thanks in advance.

AG3

4

3 回答 3

2

stringByReplacingOccurrencesOfString方法NSString有一个 NSRegularExpressionSearch选项,它接受与您的 Java 方法相同的模式\p{Cntrl} :

NSString *maybeHasControlCharsString = @"\nabc\r\ndef\r";
NSString *noControlCharsString =
    [maybeHasControlCharsString stringByReplacingOccurrencesOfString:@"\\p{Cntrl}"
                                       withString:@""
                                          options:NSRegularExpressionSearch
                                            range:NSMakeRange(0, [maybeHasControlCharsString length])];
NSLog(@"%@", noControlCharsString);
// Output: abcdef
于 2013-05-28T07:02:44.960 回答
2

尝试使用这个..这是用来替换字符的。

  NSString *str = @"\\p{Cntrl}AB/bar:baz\\p{Cntrl}foo";
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"\\p{Cntrl}"];
    str = [[str componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
    NSLog(@"%@", str);

否则,这用于替换整个字符串。

   NSString *str = @"\\p{Cntrl} This is a string \\p{Cntrl}";

    str = [str stringByReplacingOccurrencesOfString:@"\\p{Cntrl}"
                                             withString:@""];

        NSLog(@"%@", str);
于 2013-05-28T06:14:56.253 回答
0

尝试:

NSString *noControlCharsString = [maybeHasControlCharsString stringByTrimmingCharactersInSet:controlCharacterSet];

编辑正如 Martin R 正确地说,上面只删除了任何前导或尾随匹配。

这是一个从字符串中删除所有匹配项的类别方法:

- (NSString *)stringByStrippingCharactersInSet:(NSCharacterSet *)set {
    NSString *r = [self stringByTrimmingCharactersInSet:set];
    NSArray *components = [r componentsSeparatedByCharactersInSet:set];
    components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self <> ''"]];
    return [components componentsJoinedByString:@""];
}
于 2013-05-28T07:20:39.533 回答