Logstash if statement with regex example

Shawn Sim picture Shawn Sim · Feb 20, 2017 · Viewed 26.7k times · Source

Can anyone show me what an if statement with a regex looks like in logstash?

My attempts:

if [fieldname] =~ /^[0-9]*$/

if [fieldname] =~ "^[0-9]*$"

Neither of which work.

What I intend to do is to check if the "fieldname" contains an integer

Answer

Will Barnwell picture Will Barnwell · Feb 20, 2017

To combine the other answers into a cohesive answer.

Your first format looks correct, but your regex is not doing what you want.

/^[0-9]*$/ matches:

^: the beginning of the line

[0-9]*: any digit 0 or more times

$: the end of the line

So your regex captures lines that are exclusively made up of digits. To match on the field simply containing one or more digits somewhere try using /[0-9]+/ or /\d+/ which are equivalent and each match 1 or more digits regardless of the rest of the line.

In total you should have:

if [fieldname] =~ /\d+/ {
   # do stuff
}