Regex find first occurance of either of two strings C# -


i need find whether "and" and/or "or" exist in string , if so, replace first occurrence "where".

examples

and item = 'blah' and replaced where.

and item = 'blah' or product = 'foo' and replaced where.

or item = 'blah or item = 'foo' first occurrence of or replaced where.

if neither , nor or exist leave string is.

i have following works if string contains both , and or, if string contains , not work because y equal -1 , x < y going false. it's been doing head, plus late here, charged caffeine appreciated.

private string replacefilter(string filter) {     int x = filter.indexof("and");     int y = filter.indexof("or");     string regesc = (x != -1 && x < y) ? "and" : "or";      var regex = new regex(regex.escape(regesc));     return regex.replace(filter, "where", 1); } 

edit in response @luaan, aware of sql injection , have taken proper steps adding parameters correct way, have excluded part of code, because has no relevance question. @ stage need build string.

cheers.

use regex

and|or 

to search , or or , use this overload of regex replace method follows ensure replace first one:

var output = new regex("and|or").replace(input, "where", 1); 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -