# Match multiple 4 digit numbers in field

**URL:** <https://discuss.elastic.co/t/match-multiple-4-digit-numbers-in-field/264494>\
**Category:** Logstash\
**Created:** [February 16, 2021, 11:35pm UTC](https://discuss.elastic.co/t/match-multiple-4-digit-numbers-in-field/264494 "2021-02-16T23:35:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Deny7](https://avatars.discourse-cdn.com/v4/letter/d/e0b2c6/32.png) [@Deny7](https://discuss.elastic.co/u/Deny7)\
**Post date:** [February 16, 2021, 11:35pm UTC](https://discuss.elastic.co/t/match-multiple-4-digit-numbers-in-field/264494/1 "2021-02-16T23:35:45Z")

</div>

I need to match only 4 digit number from field "created:". If there are multiple 4 digit numbers I need to take the biggest and save it back to the field. The problem is that the field can contain strings, dashes, dots, brackets etc. Example:

```
"created:" "6.2016" -----> leave only 2016
"created:" "c2014" -----> leave only 2014
"created:" "[2010?]" -----> leave only 2010
"created:" "2000, c1994" -----> leave only the biggest one 2000
"created:" "2006 [i.e. 2007]" -----> leave only the biggest one 2007

```

Can use grok for this something like `(?<queue_id>[0-9]{4})....` or conditions in filter `if [created] =...`

How can I accomplish this?

---

<div class="post-metadata">

**Author:** ![Badger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/badger/32/25190_2.png) [@Badger](https://discuss.elastic.co/u/Badger)\
**Post date:** [February 17, 2021, 12:28am UTC](https://discuss.elastic.co/t/match-multiple-4-digit-numbers-in-field/264494/2 "2021-02-17T00:28:35Z")

</div>

grok will not match the same pattern repeatedly. I use the .scan function of a ruby string to do this You could try

```
    ruby {
        code => '
            created = event.get("created")
            if created
                matches = created.scan(/\d{4}/)
                # matches will be an array like ["2010"] or ["2000", "1994"]
                # Convert the array to integers
                matches = matches.map(&:to_i)
                event.set("mostRecentYear", matches.max)
            end
        '
    }

```

That assumes your field name is [created], not [created:]. You can overwrite [created] instead of adding a new field by changing the event.set line.

If you want to restrict the matches to strictly four digit numbers, and not match part of 123456 change the regexp to /\D\d{4}\D/

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [March 17, 2021, 12:28am UTC](https://discuss.elastic.co/t/match-multiple-4-digit-numbers-in-field/264494/3 "2021-03-17T00:28:57Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
