【问题标题】:Find numbers after specific text in a string with RegEx使用 RegEx 在字符串中查找特定文本后的数字
【发布时间】:2015-08-18 18:53:21
【问题描述】:

我有一个多行字符串,如下所示:

2012-15-08 07:04 Bla bla bla blup
2012-15-08 07:05 *** Error importing row no. 5: The import of this line failed because bla bla
2012-15-08 07:05 Another text that I don't want to search...
2012-15-08 07:06 Another text that I don't want to search...
2012-15-08 07:06 *** Error importing row no. 5: The import of this line failed because bla bla
2012-15-08 07:07 Import has finished bla bla

我想要的是在 RegularExpression(使用 PowerShell)的帮助下提取所有有错误的行号。所以我需要找到“*** Error importing row no.”和下面的“:”之间的数字,因为这总是会给我行号。

我查看了其他各种 RegEx 问题,但老实说,答案对我来说就像中文。

尝试在 http://regexr.com/ 的帮助下构建 RegEx,但到目前为止还没有成功,例如使用以下模式:

"Error importing row no. "(.?)":"

有什么提示吗?

【问题讨论】:

  • @AvinashRaj 谢谢,但这不起作用

标签: regex string powershell string-matching powershell-4.0


【解决方案1】:

试试这个表达式:

"Error importing row no\. (\d+):"

DEMO

这里需要了解量词和转义序列:

  • . 任意字符;如果您只需要数字,请使用\d;如果您指的是句点字符,则必须使用反斜杠 (\.) 对其进行转义
  • ? 零个或一个字符;这不是您想要的,因为您可以在第 10 行出现错误,并且只需要“1”
  • +一个或多个;这对我们来说就足够了
  • * 任何字符数;与.* 一起使用时必须小心,因为它会消耗您的全部输入

【讨论】:

  • 感谢您提供更多信息,帮助我更好地理解 RegEx。
【解决方案2】:

非常直接。现在,您的引用将导致您编写的正则表达式出现错误。试试这个:

$LogText = ""#Your logging stuff
[regex]$Regex = "Error importing row no\. ([0-9]*):"
$Matches = $Regex.Matches($LogText)
$Matches | ForEach-Object {
    $RowNum = $_.Groups[1].Value #(Waves hand) These are the rows you are looking for
}

【讨论】:

  • 也谢谢你。也很有效,非常感谢 PowerShell 示例,帮助我理清了问题。
【解决方案3】:

可能有多种方法,下面显示的几个简单方法可能会有所帮助:-

我将您的日志记录在一个名为 temp.txt 的文件中。

cat temp.txt | grep " Error importing row no." | awk -F":" '{print $2}' | awk -F"." '{print $2}'

OR

cat temp.txt | grep " Error importing row no." | sed  's/\(.*\)no.\(.*\):\(.*\)/\2/'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    相关资源
    最近更新 更多