Skip to main content
Solved

Split the output string value

  • August 28, 2024
  • 2 replies
  • 123 views

foreach device in network.devices

select {

  deviceName: device.name

}

For the above NQE, if I get the device names in the format “aaa_bbb_ccc”, is there a way to split the output based on the string “_” and have three different fields?

Best answer by Christopher

You can utilize the patternMatch function to split the device name string into different columns as follows:

parts(deviceName) =
patternMatch(replace(deviceName, "_", " "), `{part1:string} {part2:string} {part3:string}`);

foreach device in network.devices

select {
device: device.name,
device1: parts(device.name)?.part1,
device2: parts(device.name)?.part2,
device3: parts(device.name)?.part3,
}

Underscores in the string are replaced by spaces, since spaces are used by the patternMatch function to parse the string.

Note the (?) after the parts(device.name) function is called. This allows for the condition where the output of the function is null.

2 replies

Christopher
Employee
Forum|alt.badge.img+3
  • Employee
  • 21 replies
  • Answer
  • August 28, 2024

You can utilize the patternMatch function to split the device name string into different columns as follows:

parts(deviceName) =
patternMatch(replace(deviceName, "_", " "), `{part1:string} {part2:string} {part3:string}`);

foreach device in network.devices

select {
device: device.name,
device1: parts(device.name)?.part1,
device2: parts(device.name)?.part2,
device3: parts(device.name)?.part3,
}

Underscores in the string are replaced by spaces, since spaces are used by the patternMatch function to parse the string.

Note the (?) after the parts(device.name) function is called. This allows for the condition where the output of the function is null.


Andreas
Employee
  • Employee
  • 23 replies
  • October 31, 2024

Hi @pjptsujit ,

Starting in 24.10, NQE has regex matching functions. This gives you another way to solve the above problem, like this:

testDeviceNames = ["aaa_bbb_ccc", "1_22222_33"];

foreach deviceName in testDeviceNames
let match = match(deviceName, re`(?<part1>\w+)_(?<part2>\w+)_(?<part3>\w+)`)
select {
device: deviceName,
part1: match?.part1,
part2: match?.part2,
part3: match?.part3
}

The nice thing here is that you do not need to first replace underscores with space characters. A minor improvement here, but may be helpful on more complex examples as well.