我必须反转格式字符串以提取“电子邮件”并确定正确的布尔结果。
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
更新:对不起,如果我对自己的解释太笼统了。为了更好地阐明我的意图,我创建了一个小提琴https://dotnetfiddle.net/cjPAo1
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;
var possibilities = new []
{
new KeyValuePair<string,Action>(ToRegex(required), ()=>((Action)(() => { isRequired = true;}))()),
new KeyValuePair<string,Action>(ToRegex(date), ()=>((Action)(() => { isDate = 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}");
上面的代码使用正则表达式来找到合适的匹配项。样本输出
extractedField=Email,isRequired=True,isDate=False
class Program
{
static void Main(string[] args)
{
string[] inputs = {
"The Email field is required.",
"The Username field is required.",
"The InsertDate field is not a valid date.",
"Age should be between 1 and 99."
};
Type type;
foreach (string input in inputs)
{
string word = ExtractFieldAndDeterminateType(input, out type);
Console.WriteLine(word);
}
Console.ReadLine();
}
public static string ExtractFieldAndDeterminateType(string input, out Type type)
{
string[] words = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int index = 0;
if (words[0] == "The") index = 1;
string word = words[index];
switch (word)
{
case "Email" :
type = typeof(string);
break;
case "Username":
type = typeof(string);
break;
case "InsertDate":
type = typeof(DateTime);
break;
case "Age":
type = typeof(int);
break;
default:
type = (Type)Type.Missing;
break;
}
return word;
}
}