1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.