c# - Would a regex lookaround work to match one or two numbers? -
i taking in user input (string) , checking against 3 different reg ex patterns. reason doing asynchronous validation , validation function firing on every key up. user input string concatenations, longer each iteration.
the regex should match 1 3 digit numbers, space, again 1 3 digit numbers. examples:
correct: 1 12 12 26 123 12 incorrect letter or spec character space before number (space after first set of numbers ok).
the following function works:
static void main(string[] args) { string userinput = console.readline(); list<string> patternlist = new list<string>(); patternlist.add(@"^([0-9])$"); patternlist.add(@"^[0-9]{1,3} $"); patternlist.add(@"^[0-9]{1,3} [0-9]{1,3}$"); validateinput(userinput, patternlist); } private static void validateinput(string userinput, list<string> patternlist) { regex r = null; match m = null; bool ismatch = false; foreach (var p in patternlist) { r = new regex(p); m = r.match(userinput); ismatch = m.success; if (ismatch) break; } if (ismatch) { console.writeline("you wrote: {0} thats match", userinput); console.readline(); } else { console.writeline("you wrote: {0} thats not match", userinput); console.readline(); } }
but looking see if 1 expression (instead of 3) can used. lookarounds, negative behind later in expression make sure there number preceding space?
you don't need lookaround @ all, can compress 3 regexes single one:
^([0-9]{1,3})(?: ([0-9]{1,3})?)?$
?:
means non-capture group, first matching group capture first number, , second capture group evidently second.
in case space sequence between 2 numbers arbitrary (one or more spaces, tabs, whatever), can use:
^([0-9]{1,3})(?:\s+([0-9]{1,3})?)?$
instead.
lookahead , lookbehind can evidently used, making things way more complicated , harder parse. furthermore, lookahead in many cases used and pattern, not or pattern. or pattern can implemented disjunction (|
).