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

でこれを試してください:

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

これは、PCRE および perl エンジンで動作します。

説明

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

\Kトリックの説明

于 2012-12-07T18:41:27.460 に答える