简体   繁体   中英

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

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]/

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM