2

goal

I want to retrieve only this string "14" from this message with a logstash Grok

3/03/0 EE 14 GFR 20 AAA XXXXX 50 3365.00

this is my grok code

grok{
 match => {
        field1 => [
          "(?<number_extract>\d{0}\s\d{1,3}\s{1})"       
        ]         
      }
}

I would like to match just the first match "14" but my Grok filter returns all matches:

14 20 50
baudsp
  • 4,076
  • 1
  • 17
  • 35
Vince
  • 507
  • 8
  • 21

1 Answers1

2

If you need to find the first occurrence of a number that consists of 1, 2 or 3 digits only, you may use

^(?:.*?\s)?(?<number_extract>\d{1,3})(?!\S)

Details

  • ^ - start of string
  • (?:.*?\s)? - an optional substring of any 0+ chars other than line break chars as few as possible, and then a whitespace (this enables a match at the start of the string if it is there)
  • (?<number_extract>\d{1,3}) - 1 to 3 digits
  • (?!\S) - a negative lookahead that makes sure there is a whitespace or end of string immediately to the right (enables a match at the end of the string).

Alternative solution

If you know that the number you are looking for is after a date-like field and another field, and you want to force this pre-validation, you may use

^\d+/\d+/\d+\s+\S+\s+(?<number_extract>\d+)

See the regex demo

If you do not have to check if the first field is date-like, you may simply use

^\S+\s+\S+\s+(?<number_extract>\d+)
^(?:\S+\s+){2}(?<number_extract>\d+) // Equivalent

See the regex demo here.

Details

  • ^ - start of string
  • \d+/\d+/\d+ - 1+ digits, /, 1+ digits, /, 1+ digits
  • \s+ - 1+ whitespaces
  • \S+ - 1+ chars other than whitespace
  • \s+ - 1+ whitespaces
  • (?<number_extract>\d+) - Capturing group "number_extract": 1+ digits.

Grok demo:

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563