2

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]";
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
CodeBox
  • 446
  • 4
  • 19

2 Answers2

2

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

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Note that `[A-z]` matches not only letters but some non-letters, too. See [A-z and a-zA-Z difference](http://stackoverflow.com/questions/4923380/difference-between-regex-a-z-and-a-za-z). – Wiktor Stribiżew Jul 23 '15 at 12:22
1
-\S+

Would do the same for you.

or

-[a-zA-Z0-9:]+
vks
  • 67,027
  • 10
  • 91
  • 124