0

例如,我有以下模式:
- Out{d}bytes
- In{d}bytes
- In{d}bytesOut{d}bytes
- Out{d}words
- In{d}words
- In{d}wordsOut {d} 单词,其中 {d} 是数字。

我不是case. 我怎么能根据这个文本形成类似的东西:

p => p.Out == 8 && p.In == 16 //In8bytesOut16bytes  
p => p.Out == 8*8 && p.In == 4*8 // In8Out4words  
p => p.In == 8 // In8bytes  

常用表达?任何建议都会有所帮助。提前致谢。

Match match;  
int inBytes = 0;  
int outBytes = 0;    
string pattern =   
@"(?<InOut>In|Out)(?<inBytes>\d+)bytes((?<Out>Out)(?     <outBytes>\d+)bytes)?";  
Func<string, IService, bool> predicate;  
match = Regex.Match(description, pattern);  
if ((match.Groups[4].Length > 0))  
{  
   int.TryParse(match.Groups[3].Value, out inBytes);  
   int.TryParse(match.Groups[5].Value, out outBytes);  
   predicate = p => p.In == inBytes && p.Out == outBytes;  
}  

输入是格式化字符串,取自文件。它应该满足上述模式之一。主要思想是从这个字符串中获取数字。有一个服务包含两个以字节为单位的定义InOut以字节为单位。我需要解析这个字符串并创建一个条件。
例如,我得到 In4bytesOut8bytes。我需要得到 4 和 8 并做出一个
看起来像的条件Func<string, IService, bool> predicate = p => p.In == 4 && p.Out == 8

4

1 回答 1

0

我建议您在这里使用规范模式而不是 lambda:

public class ServiceSpecification
{
    private const int BytesInWord = 8;
    public int? In { get; private set; }
    public int? Out { get; private set; }

    public static ServiceSpecification Parse(string s)
    {
        return new ServiceSpecification {
            In = ParseBytesCount(s, "In"),
            Out = ParseBytesCount(s, "Out")
        };
    }

    private static int? ParseBytesCount(string s, string direction)
    {
        var pattern = direction + @"(\d+)(bytes|words)";
        var match = Regex.Match(s, pattern);
        if (!match.Success)
            return null;

        int value = Int32.Parse(match.Groups[1].Value);
        return match.Groups[2].Value == "bytes" ? value : value * BytesInWord;
    }

    public bool IsSatisfiedBy(IService service)
    {
        if (In.HasValue && service.In != In.Value)
            return false;

        if (Out.HasValue && service.Out != Out.Value)
            return false;

        return true;
    }
}

您可以从输入字符串创建规范:

var spec = ServiceSpecification.Parse(text);

并检查是否有任何服务满足此规范:

var specs = new List<ServiceSpecification>
{
    ServiceSpecification.Parse("In8bytesOut16bytes"),
    ServiceSpecification.Parse("In8wordsOut4words"),
    ServiceSpecification.Parse("In8bytes")
};

foreach(var spec in specs)
    Console.WriteLine(spec.IsSatisfiedBy(service));
于 2013-09-09T11:27:39.723 回答