首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >目标C中的正则表达式替换问题

目标C中的正则表达式替换问题
EN

Stack Overflow用户
提问于 2019-06-27 02:17:28
回答 1查看 51关注 0票数 1

试图将所有标记大写,并在替换方面遇到麻烦。知道为什么"upperCaseString“方法不起作用吗?

代码语言:javascript
复制
NSError *error = nil;
NSMutableString *stringToCap = [NSMutableString stringWithString:@"<kaboom>stuff</kaboom>"];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(</?[a-zA-Z].*?>)" options:NSRegularExpressionCaseInsensitive error:&error];
NSMutableString *modifiedString = [NSMutableString stringWithString:[regex stringByReplacingMatchesInString:stringToCap options:0 range:NSMakeRange(0, [stringToCap length]) withTemplate:@"$1".uppercaseString]];

NSLog(@"%@", modifiedString);

产生:当我期望<kaboom>stuff</kaboom><KABOOM>stuff</KABOOM>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-27 03:14:41

stringByReplacingMatchesInString:options:range:withTemplate:不是那样工作的,最后一个参数的类型是NSString,您要传递的字符串是表达式@"$1".uppercaseString - which‘s @"$1"的结果。

一种可能的算法(伪码):

代码语言:javascript
复制
for NSTextCheckingResult *match in [regex matchesInString:... options:... range:...] do
   extract the substring at match.range from modified string
   uppercase it
   replace the substring at match.range with uppercased result
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56783045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档