Powershell 多行正则表达式
Powershell multiline regex
我正在尝试通过以下示例中的行获取完整错误:
date time somemethod EXC somenumber sometext R:System.NullReferenceException: Object reference not set to an instance of an object.
at sometext in somepath .cs:line somenumber System.NullReferenceException: Object reference not set to an instance of an object.
at sometext in Somepath .cs:line somenumber
从那以后,我想得到 EXC
到 cs:line somenumber
之后的所有内容。
01/01/01 date (mode) (status) (somenumber) (name+error)
,这里通常有一个新行继续错误消息,以字符 cs:line(数字)结束。
我设法收到错误消息,因为它总是以 EXC 开头(所以正则表达式是 EXC .*
,但是我无法通过代码获得完整的消息。我只能访问 PowerShell 2.0,我正在使用以下内容公式:
$Filecontent = [io.file]::Readalltext("path to file")
$filecontent | select-string 'EXC .*' -allmatches |
foreach {$_.Matches} | Foreach {$_.Value} > errors.txt
我需要的是获取带有行号的完整错误,但我对正确的正则表达式有疑问。我不关心日期、时间、模式,正则表达式应该获得 EXC 状态并用行获取完整消息。
使用正则表达式 'EXC .*\n.*cs:line [0-9]{0,99}' 后,它会为我找到那些在一行结束后带有错误消息的消息,但是,有时我还想捕获更多的下一行。
有什么想法吗?
如果您将错误(堆栈跟踪)定义为
- 第 1 列以非空白字符开头
- 跨越多行
- 属于错误的每一行都缩进 3 个空格
那么捕获此类块的正则表达式如下所示:
(?m)^\S.*(\s*^ \S.*)+
在您检索到一个完整的堆栈跟踪块之后,您可以在第二步中使用类似这样的方法来选择行号:
at (.*?) in (.*?):line (\d+)
表达式分解为:
(?m) # inline flag: multiline mode
^ # start-of-line
\S # a non-whitespace character
.* # anything up to the end of the line
( # group 1
\s* # any number of whitespace (this matches newline character)
^ # start-of-line
# 3 spaces
\S # a non-whitespace character
.* # anything up to the end of the line
)+ # end of group 1, repeat at least once
我正在尝试通过以下示例中的行获取完整错误:
date time somemethod EXC somenumber sometext R:System.NullReferenceException: Object reference not set to an instance of an object.
at sometext in somepath .cs:line somenumber System.NullReferenceException: Object reference not set to an instance of an object.
at sometext in Somepath .cs:line somenumber
从那以后,我想得到 EXC
到 cs:line somenumber
之后的所有内容。
01/01/01 date (mode) (status) (somenumber) (name+error)
,这里通常有一个新行继续错误消息,以字符 cs:line(数字)结束。
我设法收到错误消息,因为它总是以 EXC 开头(所以正则表达式是 EXC .*
,但是我无法通过代码获得完整的消息。我只能访问 PowerShell 2.0,我正在使用以下内容公式:
$Filecontent = [io.file]::Readalltext("path to file")
$filecontent | select-string 'EXC .*' -allmatches |
foreach {$_.Matches} | Foreach {$_.Value} > errors.txt
我需要的是获取带有行号的完整错误,但我对正确的正则表达式有疑问。我不关心日期、时间、模式,正则表达式应该获得 EXC 状态并用行获取完整消息。
使用正则表达式 'EXC .*\n.*cs:line [0-9]{0,99}' 后,它会为我找到那些在一行结束后带有错误消息的消息,但是,有时我还想捕获更多的下一行。 有什么想法吗?
如果您将错误(堆栈跟踪)定义为
- 第 1 列以非空白字符开头
- 跨越多行
- 属于错误的每一行都缩进 3 个空格
那么捕获此类块的正则表达式如下所示:
(?m)^\S.*(\s*^ \S.*)+
在您检索到一个完整的堆栈跟踪块之后,您可以在第二步中使用类似这样的方法来选择行号:
at (.*?) in (.*?):line (\d+)
表达式分解为:
(?m) # inline flag: multiline mode
^ # start-of-line
\S # a non-whitespace character
.* # anything up to the end of the line
( # group 1
\s* # any number of whitespace (this matches newline character)
^ # start-of-line
# 3 spaces
\S # a non-whitespace character
.* # anything up to the end of the line
)+ # end of group 1, repeat at least once