简体   繁体   中英

Capture two strings in multi-line error message

I have created a build package for AtomBuilder which I would like to extend to capture the file path and line number in which an error occurred. I have not been able to find a working RegEx pattern for this.

Here's what an error message commonly looks like:

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

I'm really just after the the last line, since the amount of lines before that can differ, depending on the error. I need to capture the file path (Windows and Unix) between the quotes and the digit for the line number.

Here's what I have tried:

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

You could capture groups \\1 and \\2 to obtain filepath and line no using following regex.

Regex: Error.*"(.*)".*(\\d+)

Regex101 Demo

Try using capture groups to match parts that you need

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 Demo: https://jsfiddle.net/moogs/zuodcsL7/

Regex101 Demo: https://regex101.com/r/wU0aH4/1

Here's what I ended up using:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM