today came across problem: trying check errors of software in order provide right behavior of program when incurs in error.
i had check if user exists in database.
the problem back-end doesn't provide errorid have check errors text.
errors displayed this:
the user name exists!
the switch statement this:
switch (error.text) { case "user test exists": console.writeline("the user exists"); //this test behaviour. break; default: console.writeline("i couldn't behave in way :<"); }
as can imagine names different (it's unique field in db), word "test" in case statement should name of user.
can dynamically change string?
seems regex trick. i've built regex based off pattern:
the user name exists!
where name
can value. regex is:
(the user .* exists)
to use you'll this:
regex.ismatch(error.text, "(the user .* exists)", regexoptions.ignorecase)
which return true
or false
based on match. now, can't done in switch, run value through number of regexes determine matched. 1 thing might consider extension method. consider one:
public static class regexextensions { private static readonly regex usernamealreadyexists = new regex("(the user .* exists)", regexoptions.ignorecase | regexoptions.compiled); public static bool isusernamealreadyexists(this string inputvalue) { return usernamealreadyexists.ismatch(inputvalue); } }
the usage nice:
if (error.text.isusernamealreadyexists()) { // }
the extension method nice way of working through it. it's encapsulated , keep usage clean. furthermore, it's easier define regex in 1 place , set compiled
making faster.