Specific regex for markdown and links

Viewed 121

I'm using markdownKit in my iOS App, because it's easier to handle a text with titles and descriptions.

I created an admin panel for fitness gym, so they can share workouts to their members. Sometimes, they were added workouts like this:

  • Exercise 1
  • Exercise 2 etc...

And because of markdown, it's was really messy. So I created this little function, in order to remove special characters (because the purpose there was not to use it for markdown).

static func escapeMarkdownCharacters(_ text: String) -> String {
      let modString = text.replacingOccurrences(of: "[#>*\\-+]", with: "\\\\$0", options: [.regularExpression])
      return modString
}

My problem now, is that YouTube links are not clickable any more: https://youtu.be/Z9GZoDq-8JU becomes https://youtu.be/Z9GZoDq\-8JU and the link cannot be opened because of that.

Is there a way to replace occurrences only if it's not in a link ?

1 Answers

You may leverage the ICU constrained-width lookbehind pattern:

of: "(?<!http\\S{0,255})[#>*+-]"

Here, it will match

  • (?<!http\S{0,255}) - a location that is not immediately preceded with http and 0 to 255 non-whitespace chars
  • [#>*+-] - either #, >, *, + or - char.
Related