2017-05-11 1 views
1

Ich habe folgende Regex:Regex mit bedingtem Wert

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

I Strings sind Parsen wie "+ Name" und "-Name" wo +/- die Richtung ist:

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 In diesem Moment funktioniert es wie folgt:

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

Ich muss in der Lage sein, es mit "Name" zu verwenden. Das Weglassen von +/- macht Direction = Asc.

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

Wie kann ich das tun?

Antwort

1

Zuerst machen Sie [+-] Teil optional, indem Sie ein Fragezeichen hinzufügen. Danach würde die "Direction" Gruppe eine leere Zeichenfolge für ein fehlendes Zeichen zurückgeben; prüfen minus statt, und legen Sie Direction.Asc sowohl für "+" und "":

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

Demo.