c# - 反转格式字符串并确定正确结果

标签 c# formatting reverse format-string

我必须反转格式字符串来提取“电子邮件”并确定正确的 bool 结果。

string input = "The Email field is required.";

string required = "The {0} field is required.";
string date = "The {0} field is not a valid date.";

bool isRequired = false;
bool isDate = false;

string extractedField;

我的期望是将值“Email”设置为“extractedField”并将“isRequired”设置为true

更新: 抱歉,如果我对自己的解释过于笼统。为了更好地阐明我的意图,我创建了一个 fiddle https://dotnetfiddle.net/cjPAo1

最佳答案

我相信我理解您的查询。您想要检查当前消息匹配哪个“表达式”,并根据它,将适当的标志设置为 true。同时检索有问题的“字段”。

实现这一目标的一种方法是

更新

根据您的评论,已更新代码以支持多个字段。

string input = "Age should be between 1 and 99.";
string required = "The {0} field is required.";
string date = "The {0} field is not a valid date.";
string range = "{0} should be between {1} and {2}.";

bool isRequired = false;
bool isDate = false;
bool isRange = false;
string extractedField;


var possibilities = new []
                    {
                        new KeyValuePair<string,Action>(ToRegex(required), ()=>((Action)(() => { isRequired = true;}))()),
                        new KeyValuePair<string,Action>(ToRegex(date), ()=>((Action)(() => { isDate = true;}))()),
                        new KeyValuePair<string,Action>(ToRegex(range), ()=>((Action)(() => { isRange = true;}))())
                    };
var result = possibilities
             .Where(x=>Regex.Match(input,x.Key).Success)
             .Select(x=> new KeyValuePair<IEnumerable<string>,Action>( 
                                            Regex.Match(input,x.Key).Groups.Cast<Group>().Where(c=>c.Name.StartsWith("Field")).Select(c=>c.Value),
                                            x.Value)).First();


var fields = result.Key;
result.Value();
Console.WriteLine($"{nameof(extractedField)}={string.Join(",",fields)},{Environment.NewLine}{nameof(isRequired)}={isRequired},{Environment.NewLine}{nameof(isDate)}={isDate}");

ToRegex 定义为

public string ToRegex(string value)
{
    var result = new List<string>();
    foreach(var item in value.Split(' '))
    {
        if(Regex.Match(item,@"{(?<Value>\d*)}").Success)
        {
            var match = Regex.Match(item,@"{(?<Value>\d*)}");

            result.Add(Regex.Replace(item,@"{(?<Value>\d*)}",$"(?<Field{match.Groups["Value"].Value}>\\S*)"));
            continue;
        }
        result.Add(item);
    };
    return string.Join(" ",result);
}

Demo Code

上面的代码使用正则表达式来查找适当的匹配。

示例输出

extractedField=Age,1,99,
isRequired=False,
isDate=False

更新

根据您的评论,要支持多个单词,您可以使用以下内容。

public string ToRegex(string value)
{
    var result = new List<string>();
    foreach(var item in value.Split(' '))
    {
        if(Regex.Match(item,@"{(?<Value>\d*)}").Success)
        {
            var match = Regex.Match(item,@"{(?<Value>\d*)}");

            result.Add(Regex.Replace(item,@"{(?<Value>\d*)}",$"(?<Field{match.Groups["Value"].Value}>[\\S ]*)"));
            continue;
        }
        result.Add(item);
    };
    return string.Join(" ",result);
}

关于c# - 反转格式字符串并确定正确结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60475565/

相关文章:

c# - 零填充 TimeSpan.ToString(String)

ide - 为什么 IDE 不支持动态格式化?

Java - 不带格式的输出数组

java - 反转字符串和大小写

c++ - boost::iterator_range 的 rbegin()

c# - UWP : Binding selected date in calendarview

c# - 如何从 FFMPEG 获取 c# 中的帧进度

c# - 如何从 C# 启动外部可执行文件并在进程结束时获取退出代码

java - 打印数组的反转时出现 ArrayIndexOutOfBoundsException

c# - 如何获得*互联网* IP?