2

我需要一个正则表达式来匹配一个句子中括号内的单词。例如:

"this is [stack]overflow. I [[love]this[website]]."

我想从上面的句子中匹配的是单词 stack、love 和 website。

我已经尝试了以下正则表达式\[(.*[^\]\[])\],但它不起作用。

4

2 回答 2

4

以下应该有效:

\[([^\[\]]*)\]

示例:http ://www.rubular.com/r/uJ0sOtdcgF

解释:

\[           # match a literal '['
(            # start a capturing group
  [^\[\]]*     # match any number of characters that are not '[' or ']'
)            # end of capturing group
\]           # match a literal ']'
于 2012-12-07T18:40:39.963 回答
1

Try doing this in a :

$ echo 'this is [stack]overflow. I [[love]this[website]]' |
    grep -oP '\[+\K[^\]]+'
stack
love
website

This works with PCRE & perl engines.

EXPLANATIONS

\[           # match a literal '['
+            # one (preceding character) or more
\K           # "reset" the regex to null
[^]          # excluding class, here a literal \]
\]           # match a literal ']'

explanations about \K trick

于 2012-12-07T18:41:27.460 回答