user2053760 user2053760 - 1 year ago 57
Objective-C Question

ios Replace subStrings with a pattern

I have a very long string and it contains some information that I do not want. For example, it constantly has something like:

"<span class=/"phrasedesc/">....some text......</span phrasedesc>"

and I would like to remove all the substrings begin with
"<span class=/"phrasedesc/">"
and ends with
"</span phrasedesc>"
, no matter what's between.

Any one can help me with this? Thank you.

Answer Source

Try this, it worked for me. :)


let re = try! NSRegularExpression(pattern: "(.*)(《span class=\"phrasedesc\"》.*《\\/span phrasedesc》)(.*)", options: .AnchorsMatchLines)

let stringToMatch = "adfasdfasdf《span class=\"phrasedesc\"》ajshdfljkahsdkjf  《/span phrasedesc》asdfasdfasdfasdf"

let matches = re.matchesInString(stringToMatch, options: .WithTransparentBounds , range: NSRange(location: 0, length: stringToMatch.characters.count))

re.stringByReplacingMatchesInString(stringToMatch, options: .ReportCompletion, range: NSMakeRange(0, stringToMatch.characters.count), withTemplate: "$1$3")


    NSString *stringToBeTrimmed = @"adfasdfasdf《span class=\"phrasedesc\"》ajshdfljkahsdkjf  《/span phrasedesc》asdfasdfasdfasdf";

    NSString *pattern = @"(.*)(《span class=\"phrasedesc\"》.*《\\/span phrasedesc》)(.*)";

    NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionAnchorsMatchLines error:nil];

    NSString * yourResultingString =  [expression stringByReplacingMatchesInString:stringToBeTrimmed options:NSMatchingReportCompletion range:NSMakeRange(0, stringToBeTrimmed.length) withTemplate:@"$1$3"];