Firstly, here's my main question. How do I define a regex to extract relative file names from html code?
If that interests you, here's my problem...
I'm developing a program that manages templating of html files, and I need a way to handle relative filenames within the html. For example, file C:\dir\index.html acts as a template file, containing html code to be used across other html files that depend upon it, eg. C:\dir\subdir\index.html. Now most of the html code can simply be copied across as is, however any relative filenames within C:\dir\index.html, will obviously no longer point to the right place if copied directly into C:\dir\subdir\index.html. So, I need to adjust any relative file names to suit the new file location.
The current approach I'm working on is to use a regex to identify any filenames in the original html, then in the program code (C#), check that the retrieved file name exists and is relative. This is because I don't trust my regex skills to get this right perfectly, so I'm designing the regex to capture anything that might be a filename, and then double check it in the code.
Currently my regex looks like this:
which seems to capture any filename or url so far in testing.
A few criteria:
- needs to handle a filename anywhere, not just neatly embedded within single or double quotes
- needs to cope with filenames with embedded white space that isn't a part of the file name (eg. file name across multiple lines, which, I think, is valid in html)
- can assume that the file has an extension (which is what I've done above)
- needs to capture the whole filename and path as written in the html, but nothing else
- can be a little too inclusive, as long as anything that it detects that isn't a relative file path can be easily checked for in C# code (eg. using Path.IsPathRooted)
If anyone has any better regex's, or better solutions to my problem, that would be helpful.