Home > Net >  Regexp matching complete lines containing "error" or "warn" (case insensitive) w
Regexp matching complete lines containing "error" or "warn" (case insensitive) w

Time:01-18

I want to print the complete line from my log file to the user for every line containing WARN or ERROR (case insensitive)

[01-17|18:53:38.179] INFO server/server.go:381 this would be skipped
[01-17|18:53:38.280] INFO server/server.go:620 this also
[01-17|18:53:41.180] WARN server/server.go:388 Something is warned, so show this
[01-17|18:53:41.394] WARN server/server.go:188 Something reported an ->error<-
[01-17|18:53:41.395] ERROR server/server.go:191 Blabla
[01-17|18:53:41.395] DEBUG server/server.go:196 Obviously skipped
[01-17|18:53:41.395] DEBUG server/server.go:196 This debug contains an ->error<- so match this
[01-17|18:53:41.395] WARN server/server.go:198 You get the idea

I naively started with

errorRegEx := regexp.MustCompile(`(?is)error|warn`)

Which would just print (from a different run, might not exactly match the above example)

WARN
error

Then I thought I'd change this to match a bit more:

errorRegEx := regexp.MustCompile(`(?is).*error.*|.*warn.*`)

But this didn't print anything at all

How can I get the complete line, and all lines, where either WARN or ERROR (case insensitive) would match?

CodePudding user response:

You could use this Regex:

/^.*(error|warn).*$/igm

Full example and description on Regex101.com

const data = `[01-17|18:53:38.179] INFO server/server.go:381 this would be skipped
[01-17|18:53:38.280] INFO server/server.go:620 this also
[01-17|18:53:41.180] WARN server/server.go:388 Something is warned, so show this
[01-17|18:53:41.394] WARN server/server.go:188 Something reported an ->error<-
[01-17|18:53:41.395] ERROR server/server.go:191 Blabla
[01-17|18:53:41.395] DEBUG server/server.go:196 Obviously skipped
[01-17|18:53:41.395] DEBUG server/server.go:196 This debug contains an ->error<- so match this
[01-17|18:53:41.395] WARN server/server.go:198 You get the idea`;

console.log(data.match(/^.*(error|warn).*$/igm))

CodePudding user response:

Look for the ERROR and WARN tokens after the first space on the line:

 errorRegEx := regexp.MustCompile(`^[^ ]* (?:ERROR|WARN) .*`)
  • Related