我相信我理解您的查询。您想检查当前消息匹配的“表达式”,并根据它,将适当的标志设置为 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);
}