javascriptregexmatch

Javascript Regex matching multiple repeating blocks


I need to match a series of repeating VirtualHost configs in Javascript, Example:

...
# First VHost...
<VirtualHost *:80 *:8082>
    # Any number of configs
    # and set up options for
    # Apache
</VirtualHost>

# Second VHost...
<VirtualHost *:80 *:8082>
    # Any number of configs
    # and set up options for
    # Apache
</VirtualHost>

# Third VHost...
<VirtualHost *:80 *:8082>
    # Any number of configs
    # and set up options for
    # Apache
</VirtualHost>
....

My current RegEx Pattern is:

/<VirtualHost[*:0-9\s]+>([\S\s]+)<\/VirtualHost>/g

I understand that my capturing group is the reason I am getting only one matched set (the whole string as it were), but I don't know how else to capture what is between the VirtualHost blocks.

What I'd like to put output is an array that is: [<first vhost>, <second vhost>, <third vhost>, ...] Any help would be wonderful!


Solution

  • Use non-greedy regex:

    /<VirtualHost[*:0-9\s]+>([\S\s]+?)<\/VirtualHost>/g
    

    RegEx Demo

    Difference is [\S\s]+? vs [\S\s]+ which is a greedy rexex and matches as much as possible until last </VirtualHost> is matched.