Search code examples
iosswiftregexmacosnsregularexpression

Regular expression to remove link in String in Swift


I have bunch of strings I receive from service and need to alter the text to extract and remove 3 types of link as mentioned below

anchor - [anchor:info]Account Details[/anchor]
action -  [action:contact]Contact info[/anchor]
link-to - [link-to:register]Create An Account[/link-to]

Example full length text from service:

  1. "There's a problem with your [anchor:info]Account Details[/anchor]."
  2. "There's a problem with your [anchor:rewards]Sign Up For Rewards[/anchor]."
  3. "We didn't recognize this account. Please re-enter your email or [link-to:register]Create An Account[/link-to]."

And the expected result should be:

  1. "There's a problem with your Account Details."
  2. "There's a problem with your Sign Up For Rewards."
  3. "We didn't recognize this account. Please re-enter your email or Create An Account."

I figured I will use replacingOccurrences function to achieve this. But I haven't cracked the regular expression for my required format.

let aString = "There's a problem with your [anchor:info]Account Details[/anchor]."
let newString = aString.replacingOccurrences(of: "regex here", with: " ", options: .regularExpression, range: nil)

I can either have 3 separate regex to match the 3 cases or have one regex which can handle below:

[any_link_type:any_identifier]Any Text[/any_link_type]

Can some regex gurus help me with this?


Solution

  • Try this pattern ^([^[]+)\[([^:\]]+)[^\]]*\]([^[]+)\[\/\2\]

    And replace it with \1\3.

    Explanation:

    ^ - beginning of the string

    ([^[]+) - match one or more characters other than [ and store in capturing group

    \[ - match [ literally

    ([^:\]]+) - match one or more characters other than : or ] and store in capturing group

    [^\]]* - match zero or more characters other than ]

    \] - match ] literally

    ([^[]+) - match one or more characters other than [ and store in capturing group

    \[\/ - match [/ literally

    \2 - match the same text as was matched in second capturing group (so it matches closing tag, like anchor)

    \] - match ] literally

    Demo