【问题标题】:how to alter a string with NSRegularExpression如何使用 NSRegularExpression 更改字符串
【发布时间】:2013-10-25 14:14:13
【问题描述】:

我是 Objective-c 的初学者。

我有以下NSMutableString stringVal=@"[abc][test][end]";

为了删除最后一个 [] 片段(例如 [end]),我应该使用什么最佳方法?

我有这个代码:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\[]" options:0 error:NULL];
    NSArray *matches = [regex matchesInString:stringVal options:0 range:NSMakeRange(0, [stringVal length])];
    for (NSTextCheckingResult *match in matches) {
        ?? what should i do here?
    }

【问题讨论】:

  • 好的,我的理解是你想删除字符串结尾,然后你想在你的数组上添加对吗??

标签: objective-c nsregularexpression nsmutablestring


【解决方案1】:

我认为你应该使用这个正则表达式模式"\\[.*?]" 然后你会得到三个匹配项

['[abc]', '[test]', '[end]']

然后可以得到第三个匹配的范围(检查你至少有三个)

NSMutableString* stringVal= [NSMutableString stringWithString:@"[abc][test][end]"];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[.*?]" options:0 error:NULL];
NSArray *matches = [regex matchesInString:stringVal options:0 range:NSMakeRange(0, [stringVal length])];
NSTextCheckingResult* match = matches[2];

NSMutableString* substring = [[stringVal substringToIndex:match.range.location] mutableCopy];

【讨论】:

  • 我有以下工作:未知的转义序列“”\“]”。 stringVal 也是一个 NSMutableString。如果我想让子字符串也成为 NSMutableString,我应该怎么写?
  • 它不工作。它不显示任何 [match rangeAtIndex:0]
  • NSRegularExpression regex = [NSRegularExpression regularExpressionWithPattern:@"[.?]" options:0 error:NULL]; NSArray *matches = [regex matchesInString:stringval options:0 range:NSMakeRange(0, [stringval length])]; NSTextCheckingResult *match = [匹配 lastObject]; NSRange matchRange = [匹配范围]; NSLog(@"match is: %@",[stringval substringWithRange:[match rangeAtIndex:0]]);
  • 终于得到了xcode,没有意识到你需要转义字符串和re,所以在[之前有两个反斜杠。相应地改变了答案
【解决方案2】:

jbat 是正确的,您应该修改正则表达式。之后,你只需要最后一场比赛,所以你可以使用

NSTextCheckingResult *match = [matches lastObject]; // Get the last match
NSRange matchRange = [match range]; // Get the position of the match segment
NSString *result = [stringVal stringByReplacingCharactersInRange:matchRange  withString:@""]; // Replace the segment by an empty string.

【讨论】:

  • 是的,我刚刚添加了您的建议。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-07-01
  • 2011-09-29
  • 1970-01-01
  • 2016-07-25
  • 2015-02-03
  • 2011-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多