c# - Match occurrences of a character before a control character, match zero if control character not present -


i working on functionality allow user specify "wildcarded" path items in folder hierarchy , associated action performed when item matches path. e.g.:

    path         action     -----------  -------  1. $/foo/*/baz  include  2. $/foo/bar/*  exclude 

now example above, item @ $/foo/bar/baz match both actions. given want provide crude score of specificity of wildcarded path, based on "depth" first wildcard character occurs at. path depth win. importantly, * bounded forward slashes (/*/) allowed wildcard (except when @ end /*) , number specified @ various points in path.

tl;dr;

so, think regex count number of forward slashes prior first * way go. number of reasons, there no wildcard in path match of forward slashes zero. have got following negative lookbehind:

 (?<!\*.*)/ 

which works fine when there wildcards (e.g. 2 forward slash matches path #1 above , 3 #2), when there no wildcard naturally matches forward slashes. sure simple step match none due rusty regex skills stuck.

ideally academic point of view i'd see if single regex capture this, bonus points offered more elegant solution problem!

this 1 way it:

match = regex.match(subject,      @"^       # start of string     (         # match , capture in group number 1...      [^*/]*   #  number of characters except slashes or asterisks      /        #  followed slash     )*        # 0 or more times.     [^*/]*    # match additional non-slash/non-asterisk characters.     \*        # match asterisk",      regexoptions.ignorepatternwhitespace); 

now regex fails match if there no asterisk in subject string (score of 0). if regex matches, can sure there @ least 1 asterisk in it.

the clever thing .net regexes, unlike other regex flavors, can count how many times repeated capturing group has matched (most other regex engines discard information), allows determine number of slashes before first asterisk in string.

that information can found in

match.groups[1].captures.count 

(of course means "no slashes before first asterisk" , "no asterisk @ all" both score 0, appears you're asking in question, i'm not sure why make sense)


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -