regex - 仅使用起始值匹配多行事件

标签 regex powershell

我正在尝试匹配事件,其中判断事件何时开始和结束的唯一方法是使用多行事件中的标题或第一个值(例如 START--)。基本上,使用标题作为结束 anchor 来获取整个事件。另外,最后一个事件将在文件末尾结束,因此该事件没有 anchor 。我不太确定如何进行这项工作。

事件示例(行与行之间没有空格)

START--random stuff here 
more random stuff on this new line 
more stuff and things 
START--some random things 
additional random things 
blah blah 
START--data data more data 
START--things 
blah data
$FileContent | select-string '^START--(.*?)^START--' -AllMatches | Foreach {$_.Matches} | Foreach {$_.Value}

最佳答案

您可以将文件读入单个变量(例如,可以通过将 -Raw 选项传递给 Get-Content 来完成)并在以 START-- 开头的行开头,但第一行:

$contents = Get-Content 'your_file_path' -Raw
$contents -split '(?m)^(?!\A)(?=START--)'

will yield

enter image description here

正则表达式详细信息

  • (?m) - 多行选项打开
  • ^ - 现在,由于 (?m)
  • ,它匹配行的开头
  • (?!\A) - 不是整个字符串/文本的开头
  • (?=START--) - 紧随 START-- 子字符串的位置。

关于regex - 仅使用起始值匹配多行事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57417368/

相关文章:

regex - 错误: “Function REGEXEXTRACT parameter 2 value ” …"is not a valid regular expression

php - 修改单个 RegEx 以匹配字符串中的中间项

r - 如果字符串列中存在 $ 符号,则子集数据框

PHP 正则表达式 : exclude href anchor tags

c# - 使用 PowerShell 查找最接近的 System.Color 实例

PowerShell:检测脚本函数中的错误

powershell - 如何将 PowerShell 变量返回到 VBScript

powershell - 有关Powershell Compare-Object的问题-将输出捕获到变量的问题

git - 无法通过 SSH 连接到自定义端口上的 Gitlab 容器

r - 需要正则表达式逻辑