Remove complete html tag with content

Viewed 59

I have this content:

var a = "Hello <sup foot_note=\"81277\">1</sup> World"

And I want to remove the whole html tag: <sup foot_note=\"81277\">1</sup>

I tried it with this code:

let str1 = getText().replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
var str2 = str1.replacingOccurrences(of: "&[^;]+;", with: "", options: .regularExpression, range: nil)

This does not remove the "1", so I get "Hello 1 World". How can I solve this?

1 Answers

For the current example, you can use

a.replacingOccurrences(of: #"(?s)\s*<(\w+)(?:\s[^>]+)?>.*?</\1>"#, with: "", options: .regularExpression, range: nil) # #1
a.replacingOccurrences(of: #"(?i)\s*<sup(?:\s[^>]+)?>[^<]*</sup>"#, with: "", options: .regularExpression, range: nil) # #2

Note that regexps are bad at removing arbitrary HTML tags (Line #1 above), as they can be nested. The first solution might actually be rather dangerous

Thus, if you just want to remove sup tags with their contents (that usually do not contain nested tags and are not nested themselves), you can use Line #2 regex.

See the regex demo.

Details

  • (?i) - Case insensitive search
  • \s* - zero or more whitespaces
  • <sup - <sup string
  • (?:\s[^>]+)? - an optional occurrence of a whitespace and then one or more chars other than >
  • > - a > char
  • [^<]* - zero or more chars other than <
  • </sup> - a </sup> text.
Related