Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Gsub with single and multiple square brackets

I have a string which includes square brackets, sometimes this is a set of double square brackets and sometimes a set of single followed by a double set. My issue my issue here is that when i try to use gsub to remove these I can’t seem to remove both sets, depending on my code i either remove the single or the double set.

df$names
Name, Example [A] [[UK
Name2, AnotherExample [[USA

What I am trying to achieve:

df$names
Example Name
AnotherExample Name

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To do this I have tried the following; (the top option removes the double square brackets whilst the bottom line removes the single)

gsub("(.+)\\, (.+) \\[.+", "\\2 \\1", df$names)
gsub("(.+)\\, (.+)", "\\2 \\1", df$names)

>Solution :

In the second replacement, match anything except a bracket to make the query less "greedy".

gsub("^(.+),[[:space:]]+([^\\[]+).*$", "\\2 \\1",df$names)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading