这可能会更容易,如果风包括更强大的命令行正则表达式解释器。 findstr
适用于提供布尔匹配/不匹配或返回包含匹配的完整行,但不能与sed
或grep -o
的灵活性相匹配并仅返回该行的匹配部分。
我会做的是使用Windows脚本宿主(VBScript/JScript)的更健壮的正则表达式和字符串操作工具。下面是一个例子。蝙蝠/ JScript的混合:
@if (@CodeSection == @Batch) @then
@echo off
setlocal
set "htmlfile=test.html"
rem // invoke hybrid JScript code
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%htmlfile%"') do (
rem // do stuff with %%I
echo found: %%I
)
rem // end main runtime
goto :EOF
@end
// end batch/begin JScript chimera
var fso = WSH.CreateObject('scripting.filesystemobject'),
html = fso.OpenTextFile(WSH.Arguments(0), 1),
images = html.ReadAll().replace(/\r?\n/g, '').match(/img[^>]+?src=(['"]).+?(?=\1)/ig);
html.Close();
WSH.Echo(images.join('\n').replace(/img[^>]+?src=['"]/ig,''));
这应该匹配成功
<img src="typical.jpg">
<img class="noclick" src="class/included.png" />
<img style="border: 0"
src="tag/has/line/break.gif">
<img src="http://apostrophe/in/source's name.jpg">
<img src='single-quoted.jpg' />
...这将是很难甚至sed
或grep
。
如果你已经有了逃避的正则表达式刮特别顽固的HTML文档,你可以调用Internet Explorer作为一个COM对象来解析<img>
标签作为DOM节点。如果您尝试通过JavaScript或CSS伪元素来动态填充其图像的页面,这将会非常有用。 IE的这种调用比较慢很多,但它是一个故障安全。
@if (@CodeSection == @Batch) @then
@echo off
setlocal
set "htmlfile=test.html"
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%htmlfile%"') do (
rem // do stuff with %%I
echo %%I
)
rem // end main runtime
goto :EOF
@end
// end batch/begin JScript chimera
var fso = WSH.CreateObject('scripting.filesystemobject'),
IE = WSH.CreateObject('InternetExplorer.Application'),
htmlfile = fso.GetAbsolutePathName(WSH.Arguments(0));
IE.Visible = 0;
IE.Navigate('file:///' + htmlfile.replace(/\\/g, '/'));
while (IE.Busy || IE.ReadyState != 4) WSH.Sleep(25);
var images = IE.document.getElementsByTagName('img');
for (var i=0; i<images.length; i++) WSH.Echo(images[i].src);
IE.Quit();