【问题标题】:objective c regex convert match to uppercase before replacing目标c正则表达式在替换之前将匹配转换为大写
【发布时间】:2015-04-16 12:43:21
【问题描述】:

考虑下面的代码

NSString* originalString = @"I love regex. regex is cool.";
NSString* regexString = [NSString stringWithFormat:@"(regex)"];
NSString* replaceWithString = @"[$1]";
NSString* finalString = [htmlString stringByReplacingOccurrencesOfRegex:regexString withString:replaceWithString];

输出是:

我喜欢 [正则表达式]。 [正则表达式] 很酷。

我想要的是

我喜欢 [正则表达式]。 [正则表达式] 很酷。

即 toUpperCase() 的 $1 类型组匹配。

看来我可以使用replacementStringForResult:inString:offset:template: 做到这一点,但不知道如何。有人可以帮忙吗?

【问题讨论】:

  • 我不知道这是否适合你,但在许多语言中,你可以使用\u\1 或者\u$1

标签: objective-c regex uppercase


【解决方案1】:

您可以像这样使用RegexKit 实现您想要的:

upper = [originalString stringByMatching:@"(regex)"
                        replace:RKReplaceAll
                        withReferenceString:@"[\\U$1\\E]"]; 
// I love [REGEX]. [REGEX] is cool.

参考资料:

【讨论】:

  • 哦,我以为 NSRegularExpression 已经让 RegexKit 过时了!!让我们等待有人回答是否可以使用标准 Apple API 而不是 RegexKit
猜你喜欢
  • 2018-04-07
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多