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

时间:2022-11-25 19:32:11

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, 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?

我想我需要用look forward,例如:\ (?)=)。但是,这只指向下一个字符,而我想检查方括号之间的所有字符都不是空格。在这种情况下该怎么办?

1 个解决方案

#1


3  

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)

(捕获括号之间的所有非空格字符,并在找到的地方替换整个字符串)

#1


3  

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)

(捕获括号之间的所有非空格字符,并在找到的地方替换整个字符串)