Regular expression in Objective-C

I want to replace all tags that look like <xxxx> .

I tried this:

 - (NSString *)grabData:(NSString *)searchTerm { // Setup an error to catch stuff in NSError *error = NULL; //Create the regular expression to match against NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<.*>" options:NSRegularExpressionCaseInsensitive error:&error]; // create the new string by replacing the matching of the regex pattern with the template pattern(whitespace) NSString *newSearchString = [regex stringByReplacingMatchesInString:searchTerm options:0 range:NSMakeRange(0, [searchTerm length]) withTemplate:@""]; NSLog(@"New string: %@",newSearchString); return newSearchString; } 

But that just doesn't work. Can anyone help me?

+4
source share
2 answers

Sample <.*> Matches less than any number, including more than, and then more. This template could, for example, match the full HTML file ...

What you need is <[^>]+> [^>] - this is the set of all characters excluding more than + , "one or more", so the whole thing corresponds to less than one or more of anything other than the larger, and then more than.

+2
source

Your regular expression is incorrect.

  • <and> are metacharacters and require escaping
  • Compliance with the pattern should be. +

Based on this usage

 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\<.+\\>" options:NSRegularExpressionCaseInsensitive error:&error]; 

and he should work

0
source

Source: https://habr.com/ru/post/1388505/


All Articles