简体   繁体   中英

regex to capture optional group based on optional substring

I want to create a regex to capture optional group based on optional substring. Examples could be:

DATEF[[%d/%m/%Y %H:%M 
DATEF[[%H:%M]]
DATEF
TIME

etc.

I would like the DATE and parameter %H:%M to be captured. The expression (.*?)\\[\\[(.*?)\\]\\] works with parameters, but the optional excluded strings fail and return null.

i would suggest this one:

/^([a-zA-Z]+)(?:\\[\\[([^\\]]+)\\]\\])?$/

group 1 holds the functionname, and if a [[ is present, group 2 captures everything between [[ and ]] , if the squares are not present, group 2 won't be present at all.

EDIT:

Note the outer non-capturing group contains a capturing group:

/^([a-zA-Z]+)         #captures the command
    (?:\[\[           #matches, but not captures the opening brackets
        ([^\]]+?)     #captures the content of the brackets
    \]\])?            #matches the closing brackets
$/x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM