简单的正则表达式问题。我有一个字符串的以下格式:

this is a [sample] string with [some] special words. [another one]

提取方括号内的单词的正则表达式是什么?

sample
some
another one

注意:在我的用例中,括号不能嵌套。


当前回答

这段代码将提取方括号和圆括号之间的内容

(?:(?<=\().+?(?=\))|(?<=\[).+?(?=\]))

(?: non capturing group
(?<=\().+?(?=\)) positive lookbehind and lookahead to extract the text between parentheses
| or
(?<=\[).+?(?=\]) positive lookbehind and lookahead to extract the text between square brackets

其他回答

括号可以嵌套吗?

如果不是:\[([^]]+)\]匹配一个项目,包括方括号。反向引用\1将包含要匹配的项。如果你的正则表达式口味支持搜索,请使用

(?<=\[)[^]]+(?=\])

这将只匹配括号内的项。

这应该是正确的:

\[([^]]+)\]

(?<=\[).*?(?=\])根据上述解释工作良好。下面是一个Python示例:

import re 
str = "Pagination.go('formPagination_bottom',2,'Page',true,'1',null,'2013')"
re.search('(?<=\[).*?(?=\])', str).group()
"'formPagination_bottom',2,'Page',true,'1',null,'2013'"

在R中,试试:

x <- 'foo[bar]baz'
str_replace(x, ".*?\\[(.*?)\\].*", "\\1")
[1] "bar"
(?<=\[).+?(?=\])

将捕获没有括号的内容

(?<=\[) -[的正向回溯 . * ?-非贪婪匹配的内容 (?=\]) -正向预测]

编辑:对于嵌套括号,下面的正则表达式应该工作:

(\[(?:\[??[^\[]*?\]))