Swasti
Swasti

Reputation: 287

Regex Match with Square Bracket and letters

How do you match regex containing letters and square bracket using kusto?

I am passing level as parametre and expect it to go until the level mentioned in the path. I have the following regex pattern to match but it doesn't include square bracket.

let level=4;
let string1= "abc/def/[id]/ghi"
let regex1=replace('level',tostring(level),'/?(([-a-z0-9]+/?){level})');
let result = extract(regex1,1,string1);

Output: abc/def
Expected output: abc/def/[id]/ghi
(upto level 4, its discrading the characters once it finds square brackets

Upvotes: 1

Views: 2233

Answers (2)

The fourth bird
The fourth bird

Reputation: 163247

You could match either the characters in the character class or surround them by square brackets to match the opening one up with the closing one.

The quantifier {0,0} matches the first part, {0,1} matching a part starting with a / etc.

If the second part of the quantifier is greater than the maximum number of occurrences in the string like {0,7}, you will still get the highest level.

You can add an anchor to assert the start of the string to prevent partial matches.

^/?(?:[-a-z0-9]+|\[[-a-z0-9]+\])(?:/(?:[-a-z0-9]+|\[[-a-z0-9]+\])){0,2}

Regex demo

A broader match could be adding the square brackets to the character class, but that could possibly also match a single occurrence.

For example with a repetition of 2:

^/?[\]\[a-z0-9-]+(?:/[\]\[a-z0-9-]+){0,2}

Regex demo

In case the backslashes have to be double escaped:

^/?[\\]\\[a-z0-9-]+(?:/[\\]\\[a-z0-9-]+){0,2}

Upvotes: 0

Slavik N
Slavik N

Reputation: 5298

You should escape the square brackets by putting a double-backslash before them, like this:

let string1 = "abc/def/[id]/ghi";
let result = extract("([-a-z0-9\\[\\]]*/){1,6}", 0, string1);
print result

Result:

abc/def/[id]/

Upvotes: 5

Related Questions