【问题标题】:How to change a specific value range when multiple keys are present?存在多个键时如何更改特定的值范围?
【发布时间】:2019-03-10 00:47:42
【问题描述】:

我有这个字符串:

Avarage Age=12 <-> 25 ; Pension Age=60 <-> 72; Nationality=[UK, USA, German, France]

最终目标是应用正则表达式来更改指定字段的范围,例如:从'Age=12 &lt;-&gt; 25''Age=10 &lt;-&gt; 30'

我该怎么做?

我试过了,有两个问题:

(1) 如果我创建了一个正则表达式来搜索(例如:):/d+&lt;-&gt;d+/ig,它将返回 Age 和 Pension Age。我可以创建一个搜索 KEY=range 的正则表达式只返回范围(返回意味着我可以用另一个范围替换)?

(2) 有了这个(只返回我需要的:年龄):

NSString *pattern = @"Age=\d+<->\d+";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
                                                           options:0
                                                             range:NSMakeRange(0, [string length])
                                                      withTemplate:@"**??????**"];

如何从 withTemplate 更改整数 12 和 25?

【问题讨论】:

    标签: objective-c regex nsregularexpression


    【解决方案1】:

    你不需要任何花哨的东西。只需在用于withTemplate: 的值中包含Age=

    NSString *pattern = @"Age=\d+<->\d+";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&
    NSString *modifiedString = [regex stringByReplacingMatchesInString:string
                                                               options:0
                                                                 range:NSMakeRange(0, [string length])
                                                          withTemplate:@"Age=10 <-> 30"];
    

    【讨论】:

    • 如果我想将 10 和 30 作为参数传递给“withTemplate”?
    • 然后使用字符串格式构建模板:NSString *template = [NSString stringWithFormat:@"Age=%d &lt;-&gt; %d", lowerNum, upperNum];.
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2019-07-07
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    相关资源
    最近更新 更多