I have a string where i want to remove anything with negative values for example,
var mystring = "+colour:black +year:2015 -model:golf";
I tried using following regex but it doesn't work.
var reg = "[+A-z:0-9]";
I have a string where i want to remove anything with negative values for example,
var mystring = "+colour:black +year:2015 -model:golf";
I tried using following regex but it doesn't work.
var reg = "[+A-z:0-9]";
You can use
var result = Regex.Replace(mystring, @"\s*[-][^\s]*\s*", string.Empty);
For only positive values:
var result = Regex.Replace(mystring, @"\s*[+][^\s]*\s*", string.Empty);
For both positive and negative:
var result = Regex.Replace(mystring, @"\s*[+-][^\s]*\s*", string.Empty);
This way, you will also handle any stray hyphens with no characters but whitespace after them, and with \s*
you will trim the output string from remanining spaces.
Notes on the regex: [-+]
matches either -
or +
once, \s*
matches 0 or more whitespace, and [^\s]*
matches 0 or more characters other than whitespace.
See demo