Heisenberg Heisenberg - 11 months ago 48
R Question

Remove square brackets that don't have spaces between them

I'm trying to remove square brackets that don't have spaces between them, but keep square brackets that do. For example:

  • Match these brackets and remove them:

  • Don't match these brackets and remove them:
    help me

Note: I want to match just the brackets, not the content.

I think that I need to use look ahead, e.g.
\\[(?!= )
. However, this only looks ahead to the next character, whereas I want to check that all characters between the square brackets are not spaces. What to do in this situation?

Answer Source

The new version of stringr may be of use to you, it has a nice widget for testing out regex matching.

stringr::str_view_all(c("[please]", "[help me]"), "(\\[)\\S*(\\])")

matches [, then any number of non-space characters, then ], with the [ and ] as capture groups. I'm not sure what you want to do with them.

Update: To remove brackets, you actually want to capture what's inside and then substitute with it.

stringr::str_replace_all(c("[please]", "[help me]"), "\\[(\\S*)\\]", "\\1")
#> [1] "please"    "[help me]"

(capture any all-non-space characters between brackets, and substitute the entire string for the capture where found)