使用正则表达式在NSString中查找/替换子字符串

64
我想使用正则表达式在字符串中查找每个&*;模式的实例,并将其从中删除,以便返回原始字符串而不包含任何匹配项。还希望使用同一个函数匹配单词之间的多个空格,并改为只有一个空格。找不到这样的函数。
示例输入字符串:
NSString *str = @"123 &1245; Ross Test  12";

返回值应该是

123 Ross Test 12

将匹配此模式 "&* 或多个空格的任何内容替换为@"";

2个回答

163
NSString *string = @"123 &1245; Ross Test 12";
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);

8
在 ObjC 中,应该使用 nil 而不是 NULL。但 NULL 也可以使用,因为它是 C 语言的。 - Daniel

14

使用正则表达式在字符串扩展中进行字符串替换的代码

Objective-C

@implementation NSString(RegularExpression)

- (NSString *)replacingWithPattern:(NSString *)pattern withTemplate:(NSString *)withTemplate error:(NSError **)error {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:error];
    return [regex stringByReplacingMatchesInString:self
                                           options:0
                                             range:NSMakeRange(0, self.length)
                                      withTemplate:withTemplate];
}

@end

解决

NSString *string = @"123 &1245; Ross Test  12";
// remove all matches string
NSString *result = [string replacingWithPattern:@"&[\\d]+?;" withTemplate:@"" error:nil];
// result = "123  Ross Test  12"

或更多

NSString *string = @"123 +   456";
// swap number
NSString *result = [string replacingWithPattern:@"([\\d]+)[ \\+]+([\\d]+)" withTemplate:@"$2 + $1" error:nil];
// result = 456 + 123

Swift2

extension String {
    func replacing(pattern: String, withTemplate: String) throws -> String {
        let regex = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
        return regex.stringByReplacingMatchesInString(self, options: [], range: NSRange(0..<self.utf16.count), withTemplate: withTemplate)
    }
}

Swift3

extension String {
    func replacing(pattern: String, withTemplate: String) throws -> String {
        let regex = try RegularExpression(pattern: pattern, options: .caseInsensitive)
        return regex.stringByReplacingMatches(in: self, options: [], range: NSRange(0..<self.utf16.count), withTemplate: withTemplate)
    }
}
var string = "1!I 2\"want 3#to 4$remove 5%all 6&digit and a char right after 7'from 8(string"
do {
    let result = try string.replacing("[\\d]+.", withTemplate: "")
} catch {
    // error
}
// result = "I want to remove all digit and a char right after from string"

1
最好将函数名重命名为 - (NSString *)stringByReplacingWithPattern:(NSString *)pattern withTemplate:(NSString *)withTemplate error:(NSError **)error - allenlinli
最好将所有这些都删除 - Stas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接