【问题标题】:Capture two strings in multi-line error message在多行错误消息中捕获两个字符串
【发布时间】:2016-03-14 21:59:26
【问题描述】:

我为AtomBuilder 创建了一个构建包,我想扩展它以捕获发生错误的文件路径和行号。我无法为此找到有效的 RegEx 模式。

错误消息通常如下所示:

Processing script file: "/Users/johndoe/Projects/test.nsi" (UTF8)
Invalid command: Foo
Error in script "/Users/johndoe/Projects/test.nsi" on line 5 -- aborting creation process

我真的只是在最后一行之后,因为在此之前的行数可能会有所不同,具体取决于错误。我需要捕获引号和行号数字之间的文件路径(Windows 和 Unix)。

这是我尝试过的:

errorMatch: [
  '((.|\\n)*)Error in script "(?<file>[^"]+) on line (?<line>\\d+) -- aborting creation process'
]

【问题讨论】:

  • 信息不够。你试过什么?为什么还不够好?
  • 您可以尝试使用正则表达式,例如 /^Error.*"([^"]+)" on line (\d+)/ 应该这样做 - 但您可以提供更多信息正如 idleberg 所建议的那样。
  • @Amit 更新了帖子

标签: javascript regex javascript-objects atom-editor


【解决方案1】:

您可以使用以下正则表达式捕获组\1\2 以获取文件路径和行号。

正则表达式: Error.*"(.*)".*(\d+)

Regex101 Demo

【讨论】:

    【解决方案2】:

    尝试使用捕获组来匹配您需要的部分

    var regex = /Error in script "(.*)" on line (\d+)/;
    
    var match = message.match(regex);
    
    if (match && match.length) {
      var filepath = match[1];
      var linenumber = match[2];
    
      console.log(filepath); // /Users/johndoe/Projects/test.nsi
      console.log(linenumber); //  5
    }
    

    JSFiddle 演示:https://jsfiddle.net/moogs/zuodcsL7/

    Regex101 演示:https://regex101.com/r/wU0aH4/1

    【讨论】:

    • 我的问题不是正则表达式本身,而是让它在 AtomBuilder 中工作
    【解决方案3】:

    这是我最终使用的:

    const errorMatch = [
        '\\n(?<message>.+)\\nError in script "(?<file>[^"]+)" on line (?<line>\\d+) -- aborting creation process'
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多