我想和Excluding strings using regex中的做法差不多,但我想使用Regex来做iOS。所以我基本上想要在字符串中找到匹配项,然后从字符串中删除它们,所以如果我有这样的字符串,Hello #world @something
我想找到#world
& @something
然后将其从字符串中删除,使其变为Hello
。我已经有了这个表达式,删除了#world
和something
但不是@
,#[\\p{Letter}]+|[^@]+$
我解决了@
问题
NSString *stringWithoutAt = [input stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"@%@",atString] withString:@""];
NSString *stringWithoutTag = [input stringByReplacingOccurrencesOfString:tagString withString:@""];
因此,对于第一个,我最终得到Hello #world
,第二个得到Hello @something
。但有没有办法使用正则表达式或其他方法同时删除#world
和@something
?
答案 0 :(得分:2)
您可以通过两种方式在iPhone中使用正则表达式: -
1>使用RegExKitLIte作为框架see the tutorial
2>使用NSRegularExpression& NSTextCheckingResult
NSStirng *string=@"Your String";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"@[a-z]*#[a-z]*" options:NSRegularExpressionCaseInsensitive error:&error];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop)
{
// your statement if it matches
}];
此处@之后的任何表达式和#之后的表达式正在连接
并且在语句中您可以用空格替换它来获取表达式
如果您只是想要修改字符串,请执行以下操作: -
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0
range:NSMakeRange(0, [string length]) withTemplate:@"$2$1"];