简体   繁体   English

删除方括号之间没有空格的方括号

[英]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可能对您有用,它有一个不错的小部件来测试regex匹配。

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) (捕获方括号之间的所有非空格字符,并将整个字符串替换为找到的捕获内容)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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