Home > other >  C# regex for conditional operators example eq:2 , ne:3
C# regex for conditional operators example eq:2 , ne:3

Time:10-22

I wanted to write an regex in C# for strings which can comprise of any operator and operand value. These operators are string characters like eq for equals , ct = contains & bt for between , eq for equals.

i get strings into backend like eq=4. But during test someone tested my code with garbage values to my API and the string was eq:** 4.

Now i want to build an regex such that it will validate string against regex values like eq:5 or bt:8-9.

JUST A NOTE : exlcuding between operator no other operator should have such value like eq:4-6.

i have done this @"^\b(eq | ne | gt | lt | ge | le | ct | bt)\w\b : ? (\d | - ) ? \d"

seems im close but need some guidance to get this properly working.

Any help or suggestion is welcome.

CodePudding user response:

(eq|ne|gt|lt|ge|le|ct|bt):-?[0-9] (--?[0-9] )?

or with named group: @"(?<operator>eq|ne|gt|lt|ge|le|ct|bt):(?<firstValue>-?[0-9] )(-(?<secondValue>-?[0-9] ))?$"

demo : https://regex101.com/r/HWnIq9/1

CodePudding user response:

You can use

@"^(eq|[gln]e|[bclg]t)\s*:\s*\d (?:\.\d )?(?:-\d (?:\.\d )?)?\z"

See the regex demo. Details:

  • ^ - start of string
  • (eq|[gln]e|[bclg]t)
  • \s*:\s* - a colon enclosed with zero or more whitespaces
  • \d (?:\.\d )? - an int/float number (one or more digits and then an optional sequence of a dot and one or more digits)
  • (?:-\d (?:\.\d )?)? - an optional sequence of a -, one or more digits and then an optional sequence of a dot and one or more digits
  • \z - the very end of string.

See the difference between $ and \z anchors in .NET regex.

Edit:

It seems only for bt ranges are accepted, so you need

@"^(?:eq|[gln]e|[clg]t|(bt))\s*:\s*\d (?:\.\d )?(?(1)(?:-\d (?:\.\d )?)?)\z"
  • Related