RegEx and Functions

This is a strange question as the information I need will drive an iCinga function, but the data will be realized on iCingaWeb2-modules-maps. Please bear with me - this may take some setup to explain.

First, we want to have Location data on our devices so that they can be displayed on a GPS map. Simple enough to start with - follow https://icinga.com/2017/08/16/integrate-maps-into-icinga/. If you read through this link, please pay attention to the getHostGeoLocation function. The method to extract the first 2 characters of the host name as the Location is simply hostName.substr(1,2).

Second, we have grown our network more or less organically according to a few different naming patterns. But there is always a Building Code embedded in the hostname. Lucky me - here are a few of the hostnames:

cas-rc-1.sec.int
rc-axis-e-exterior.surv.int
sw-rc-2n.inf
wap-rc-110-a.inf.int
ups-rc-2n.inf
laundry-rc-1.vend.int
sw-rc1.inf.int
sw-rc2.inf.int

Eagle-eyed viewers will determine that rc is in fact our building code for this group of devices. Perhaps not straight forward, but simple when you understand it.

This naming convention can be expressed as a RegEx. Specifically this RegEx:

(?<=-)[a-z]{2,3}(?=-)|(?<=-)[a-z]{2,3}(?=[\d].)|^[a-z]{2,3}(?=-axis)

Perhaps now you see my problem… I need to convert hostName.substr(1,2) through some logic to parse hostnames similar to the RegEx above. In short, in all hostname cases above, I need to have the loc variable equal to rc.

At first, I though I could use a simple regex command … but that only returns true or false if the match is present. It doesn’t help me to pull the data out.

I’m not new to programming, but I am new to iCinga functions. Does anyone have a good methodology to get what I want? A simple (syntax correct) framework would help and I could fill it out from there… but I’m stuck hoping to get a shove in a good starting direction.

Thanks in advance!

Hi,

the regex() function doesn’t allow to extract matches, it only returns a boolean match. That being said, you’d need to find a different algorithm in order to extract the details, like String#split with dashes, and iterating over the elements.

You can test-drive these operations with the icinga2 console as a sandbox.

<1> => var s = "cas-rc-1.sec.int"
null
<2> => s.split("-")
[ "cas", "rc", "1.sec.int" ]
<3> => var a = s.split("-")
null
<4> => a.remove(1)
null
<5> => a
[ "cas", "1.sec.int" ]
<6> => a.join(" ")
"cas 1.sec.int"

Use all the available functions and type methods and write your own function extracting the pattern you need.

You might also create a feature request for regex allowing to extract group matches, since this is an interesting approach :slight_smile:

Cheers,
Michael

Hello there!

I’d like to point you to this issue here that you can follow if you want:

We’re currently discussing the best way to tackle this :slight_smile:

Greetings,
Feu