簡單的正則表達式問題。 我有如下格式的字符串: 正則表達式
this is a [sample] string with [some] special words. [another one]
提取方括號內單詞的正則表達式是什麼,即 this
sample some another one
注意:在個人用例中,方括號不能嵌套。 spa
這樣應該能夠了: code
\[([^]]+)\]
括號能夠嵌套嗎? ci
不然: \\[([^]]+)\\]
匹配一項,包括方括號。 向後引用\\1
將包含要匹配的項目。 若是您的正則表達式樣式支持環視,請使用 字符串
(?<=\[)[^]]+(?=\])
這隻會匹配括號內的項目。 string
您能夠全局使用如下正則表達式: it
\[(.*?)\]
說明: 引用
\\[
: [
是一個元字符,若是要按字面值進行匹配,則須要轉義。 (.*?)
:以非貪婪的方式匹配全部內容並捕獲它。 \\]
: ]
是一個元字符,若是要按字面值進行匹配,則須要轉義。 (?<=\[).+?(?=\])
將捕獲不帶括號的內容 項目
(?<=\\[)
-對[
.*?
-內容的非貪婪匹配
(?=\\])
-正向前看]
編輯:對於嵌套括號下面的正則表達式應該工做:
(\[(?:\[??[^\[]*?\]))
此代碼將提取方括號和括號之間的內容
(?:(?<=\().+?(?=\))|(?<=\[).+?(?=\])) (?: 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