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:
[anchor:info]Account Details[/anchor]
."[anchor:rewards]Sign Up For Rewards[/anchor]
."[link-to:register]Create An Account[/link-to]
."And the expected result should be:
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?
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