简体   繁体   中英

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: [ please ]
  • 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, eg \\\\[(?!= ) . 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM