簡體   English   中英

使用正則表達式在NSString中查找/替換子字符串

[英]Use regular expression to find/replace substring in NSString

我想使用正則表達式來查找正則表達式模式的每個實例Ie &*; 在我的字符串中刪除它,因此返回值是沒有任何匹配的原始字符串。 也想使用相同的函數來匹配單詞之間的多個空格,而是使用單個空格。 找不到這樣的功能。

示例輸入字符串

NSString *str = @"123 &1245; Ross Test  12";

返回值應該是

123 Ross Test 12

如果符合此模式的任何內容"&*或多個空格並將其替換為@"";

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

字符串在String擴展中使用regex替換代碼

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM