iphone - 使用 NSRegularExpression 查找和替换

标签 iphone objective-c ios

我有一个格式为 NSString *CalculationFormula = @"((Col(202)/Col(201)-1)*100"; 的字符串 我需要将所有出现的 Col(number) 替换为 ABC(number * 10)

请帮忙...

谢谢, 本

最佳答案

期望的结果存在一些含糊之处。例如,结果应该是“ABC(202 * 10)”还是“ABC(2020)”?我假设是后者。由于正则表达式相当通用,因此这里有一个 Perl 代码片段,它可以完成我认为您想要的功能,然后将其翻译为 Cocoa。我已经给出了两个,因为在进入NSRegularExpression之前更容易看到那里发生了什么。因为后者在模式中有更多的转义符。

Perl 版本:

#!/usr/bin/perl -w
use strict;


my $search_text = "((Col(202)/Col(201)-1)*100";

$search_text =~ s|Col\((?P<num>\d+)\)|ABC($+{num}0)|g;
print $search_text;

打印:((ABC(2020)/ABC(2010)-1)*100

所以,匹配模式是Col\((?P<num>\d+)\)和替换模式 ABC($+{num}0

cocoa 版本:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    NSRegularExpression *regex = nil;
    regex = [NSRegularExpression regularExpressionWithPattern:@"Col\\((\\d+)\\)" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *searchText = @"((Col(202)/Col(201)-1)*100";
    NSString *newText = [regex stringByReplacingMatchesInString:searchText options:0 range:NSMakeRange(0,[searchText length]) withTemplate:@"ABC($10)"];
    NSLog(@"new = %@",newText);
    [p release];
}

日志:

2012-09-18 12:30:26.880 Untitled[22405:707] new = ((ABC(2020)/ABC(2010)-1)*100

现在,如果我最初的假设是错误的,并且您确实希望结果中包含“num * 10”,则替换模式为:

@"ABC($1 * 10)"

关于iphone - 使用 NSRegularExpression 查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12481552/

相关文章:

iPhone - 将核心数据添加到现有项目中?

objective-c - objective-c : fix distance between images in touches moved

ios - 检测绘制路径是否为 xcode 中的圆形/矩形

objective-c - 打开文件对话框

ios - 缺少“拒绝二进制”按钮(从审核中删除此版本)

ios - UIBezierPath 未在 iPhone 6/6+ 中的 UIViews 的正确边框上绘制

ios - 原因 : '-[CNContact setSnapshot:]: unrecognized selector sent to instance 0x7fc84c8491c0'

iphone - Objective-C 类别和新 iVar

ios - 检测 GMSMapView 缩放

iphone - 如何用Core Graphics制作渐变效果?