1

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I knew it would be a simple answers. Thanks so much! I will mark as such when SO lets me. Non-greedy, learning something new!
A deeper explanation of why this works would be much appreciated. It feels too lacking to deserve an upvote.
ok I added an explanation in my answer to make it more clear.
@anubhava That's worked just fine and i learned something new today. I appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.