簡體   English   中英

正則表達式匹配多個模式

[英]Regex matching multiple pattern

我有這些

name

name[one]

name[one][two]

name[one][two][three]

我希望能夠像這樣匹配它們:

[name]

[name, one]

[name, one, two]

[name, one, two, three]

這是我嘗試過正則表達式

/([\w]+)(?:(?:\[([\w]+)\])+)?/

我只是似乎不太正確,只能得到最后一個方括號

您不能動態捕獲數量。 捕獲的數量完全等於捕獲括號對的數量( (?:...)不包括(?:...) )。 您有兩個捕獲括號對,這意味着您將獲得兩個捕獲-不多也不少。

要處理可變數量的匹配項,請使用子匹配項(如果您的語言支持,則用函數替換)或拆分。

您沒有使用編程語言來標記,所以這是我所能做到的。

您不能在正則表達式中重復組。 您可以多次寫出來。 這在方括號中最多適用於三組。 您可以根據需要添加更多內容。

(\w+)\[(\w+)\](?:\[(\w+)\])?(?:\[(\w+)\])?

這應該做([\\w]+)(?:\\[([\\w]+)\\]\\+)?

http://regex101.com/r/mF8pC8/3

與原始正則表達式的更改-刪除了多余的捕獲,並在last +之前添加了\\

    1st Capturing group ([\w]+)
        [\w]+ match a single character present in the list below
            Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
            \w match any word character [a-zA-Z0-9_]
            (?:\[([\w]+)\]\+)? Non-capturing group
        Quantifier: Between zero and one time, as many times as possible, giving back as needed [greedy]
        \[ matches the character [ literally
    2nd Capturing group ([\w]+)
        [\w]+ match a single character present in the list below
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
        \w match any word character [a-zA-Z0-9_]
        \] matches the character ] literally
        \+ matches the character + literally
    g modifier: global. All matches (don't return on first match)

您無法使用php正則表達式動態捕獲數量...

為什么不這樣寫呢? explode('[',strtr('name[one][two][three]', [']'=>''])) -它會給您想要的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM