Miguel Moura
Miguel Moura

Reputation: 39364

Regex with Conditional value

I have the following Regex:

String regex = @"^(?<Direction>[+-])(?<Property>[A-Za-z]{1}[A-Za-z0-9]*)$";

I am parsing strings like "+name" and "-name" where +/- is the direction:

public class Rule
  public Direction Direction { get; }
  public String Property { get; }
}

public enum Direction { Asc, Desc }


public static Rule Parse(String source) {

  Match match = Regex.Match(value, _pattern);

  String property = match.Groups["Property"].Value;
  Direction direction = match.Groups["Direction"].Value == "+" ? Direction.Asc : Direction.Desc;
  Rule rule = new OrderRule(property, direction);
  return true;    
}  

In this moment it is working as follows:

 "+name" => Direction = Asc and Property = Name   
 "-name" => Direction = Desc and Property = Name    

I need to be able to use it with "name". The omission of +/- makes Direction = Asc.

 "name" => Direction = Asc and Property = Name   

How can I do this?

Upvotes: 1

Views: 34

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

First, make [+-] part optional by adding a question mark after it. After that the "Direction" group would return an empty string for a missing sign; check for minus instead, and set Direction.Asc both for "+" and "":

var regex = @"^(?<Direction>[+-]?)(?<Property>[A-Za-z]{1}[A-Za-z0-9]*)$";
...
var direction = match.Groups["Direction"].Value == "-" ? Direction.Desc: Direction.Asc;

Demo.

Upvotes: 1

Related Questions