首页 > 解决方案 > 使用命令提示符获取两个文本之间的文本的正则表达式

问题描述

我正在尝试使用命令提示符和findstr命令在我的 html 文件中的 body 标记中提取内容。我的html如下

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AdminWeb</title>
  <base href="/wwwroot/admin-web/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body><app-root></app-root><script src="/wwwroot/admin-web/runtime.js"></script><script src="/wwwroot/admin-web/file1.js" nomodule></script><script src="/wwwroot/admin-web/file2.js"></script><script src="/wwwroot/admin-web/styles.js"></script><script src="/wwwroot/admin-web/vendor.js"></script><script src="/wwwroot/admin-web/main.js"></script></body>
</html>

我想要的输出是

<app-root></app-root>
<script src="/wwwroot/admin-web/runtime.js"></script><script src="/wwwroot/admin-web/file1.js" nomodule></script><script src="/wwwroot/admin-web/file2.js"></script><script src="/wwwroot/admin-web/styles.js"></script><script src="/wwwroot/admin-web/vendor.js"></script><script src="/wwwroot/admin-web/main.js"></script>

我正在尝试使用正则表达式来实现。

findstr /R (?<=<body>)(.*)(?=</body>)  test.html

但这现在在命令提示符下工作。但是这个正则表达式在 js 中工作。

提前致谢。

标签: regexpowershell

解决方案


首先,findstr不支持现代正则表达式引擎提供的所有很酷的正则表达式功能。尤其是最新的 JavaScript ECMAScript2018+ 兼容引擎,如 Chrome、Node.js 等。因此,说“这个正则表达式在 js 中工作”并不意味着相同的模式在其他任何地方都可以工作。它肯定不会在findstr.

您可能会采取艰难的方式并继续研究如何为此编写批处理脚本。但是,其他内置 Windows 应用程序有一个更简单的方法。

我强烈建议使用 Powershell,因为它为您提供了 .NET 提供的许多功能。

在这里,打开PowerShell控制台并使用

$pathToFile = 'c:\...\...\you_file.txt'
$output_file = 'c:\...\...\you_file_out.txt' 
$rx = '(?s)(?<=<body>).*?(?=</body>)'
Get-Content $pathToFile -Raw | Select-String $rx -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

注意:最好使用 IE 自动化来处理 HTML。

$output_file = 'c:\...\...\you_file_out.txt'
$url = 'http://your_site_here.tld/...'
$ie = New-Object -comobject "InternetExplorer.Application"
$ie.visible = $true
$ie.navigate($url)

while ($ie.Busy -eq $true -Or $ie.ReadyState -ne 4) {Start-Sleep 2}

$doc = $ie.Document
$tags = $doc.getElementsByTagName("body")
$tags[0].innerHTML > $output_file

推荐阅读