I am currently attempting to match a single Apache VirtualHost entry within an apache config file by the ServerName of the VirtualHost. I am doing this with python, using the re module.

Here's an example of the type of file that I am working with:

<VirtualHost *:8000>
    DocumentRoot "/path/to/dir1"
    ServerName eg1.dev
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/path/to/docroot"
    ServerName desired.dev
</VirtualHost>

<VirtualHost *:8080>
    DocumentRoot "/path/to/dir3"
    ServerName eg2.dev
</VirtualHost>


I want to match the VirtualHost with a ServerName of desired.dev. So the match I am aiming for is:

<VirtualHost *:80>
    DocumentRoot "/path/to/docroot"
    ServerName desired.dev
</VirtualHost>


I assumed this would be fairly simple with a regex but I can't figure out how to do it. I currently have:

<VirtualHost \*:[0-9]*>.*?ServerName +desired\.dev.*?</VirtualHost>

But the issue with this being that it matches the very first <VirtualHost..., matches the ServerName and stops matching at the end of the closing tag of the desired VirtualHost.

I'm aware that there are probably python modules for parsing Apache config files but I do not wish to use anything from outside of the standard library. If attempting this with regex is a terrible idea, are there any alternatives?

有帮助吗?

解决方案

<VirtualHost \*:[0-9]*>(?:.(?!</VirtualHost))*?ServerName +desired\.dev(?:(?!</VirtualHost).)*?</VirtualHost>

Try that, it uses a lookahead to ensure it's not running over any VirtualHost closing tags.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top