使用正则表达式在NSString中查找/替换子字符串 [英] Use regular expression to find/replace substring in NSString

查看:480
本文介绍了使用正则表达式在NSString中查找/替换子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用正则表达式来查找正则表达式模式的每个实例。我的字符串中的& *; 并将其删除,因此返回值是没有任何匹配项的原始字符串。也想使用相同的函数来匹配单词之间的多个空格,而是使用单个空格。找不到这样的功能。

I would like to use regular expression to find every instances of a regular expression pattern I.e. &*; in my string and remove that from so the return value is the original string without any of the matches. Also would like to use the same function to match multiple spaces between words and have a single space instead. Could not find such a function.

示例输入字符串

NSString *str = @"123 &1245; Ross Test  12";

返回值应为

123 Ross Test 12

如果符合此模式的任何内容& * 或多个空格并替换为 @;

If anything matching this pattern "&* or multiple white spaces and replaces it with @"";

推荐答案

NSString *string = @"123 &1245; Ross Test 12";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"&[^;]*;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
NSLog(@"%@", modifiedString);

这篇关于使用正则表达式在NSString中查找/替换子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆