简单的正则表达式问题。我有一个字符串的以下格式:
this is a [sample] string with [some] special words. [another one]
提取方括号内的单词的正则表达式是什么?
sample
some
another one
注意:在我的用例中,括号不能嵌套。
简单的正则表达式问题。我有一个字符串的以下格式:
this is a [sample] string with [some] special words. [another one]
提取方括号内的单词的正则表达式是什么?
sample
some
another one
注意:在我的用例中,括号不能嵌套。
当前回答
如果你想要填充方括号a-z之间的小字母
(\[[a-z]*\])
如果你想要小写字母a-zA-Z
(\[[a-zA-Z]*\])
如果你想要小写字母和数字字母a-zA-Z0-9
(\[[a-zA-Z0-9]*\])
如果你想要所有在方括号之间的东西
如果你想要文字,数字和符号
(\[.*\])
其他回答
在R中,试试:
x <- 'foo[bar]baz'
str_replace(x, ".*?\\[(.*?)\\].*", "\\1")
[1] "bar"
这段代码将提取方括号和圆括号之间的内容
(?:(?<=\().+?(?=\))|(?<=\[).+?(?=\]))
(?: 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
(?<=\[).+?(?=\])
将捕获没有括号的内容
(?<=\[) -[的正向回溯 . * ?-非贪婪匹配的内容 (?=\]) -正向预测]
编辑:对于嵌套括号,下面的正则表达式应该工作:
(\[(?:\[??[^\[]*?\]))
这应该是正确的:
\[([^]]+)\]
如果有人想匹配并选择一个在方括号内包含一个或多个圆点的字符串,如“[fu.]”。Bar]"使用以下语句:
(?<=\[)(\w+\.\w+.*?)(?=\])
正则表达式测试器