Обратный формат строки и определить правильный результат - PullRequest
2 голосов
/ 01 марта 2020

Мне нужно перевернуть строку формата, чтобы извлечь «Email» и определить правильный логический результат.

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» для «extractField» и «isRequired» было равно true

ОБНОВЛЕНИЕ: Извините, если я слишком обобщенно объяснил себя. Чтобы лучше уточнить мои намерения, я создал скрипку https://dotnetfiddle.net/cjPAo1

Ответы [ 3 ]

1 голос
/ 01 марта 2020

Используя Regex.Match, функцию ExtractFieldAndDeterminateType можно записать в виде:

public static string ExtractFieldAndDeterminateType(string input, out Type type)
{
    var extractedField = "";
    string required = "The (.*) field is (.*).";
    //string date = "The (.*) field is not a (.*)."; => Not needed
    string range = "(.*)(?= should be between)";
    type = Type.Unknown;

    var match = Regex.Match(input, required);
    if (match.Success)
    {
        extractedField = match.Groups[1].Value;
        switch (match.Groups[2].Value)
        {
            case "required":
                type = Type.Error;
                break;
            case "not a valid date":
                type = Type.Date;
                break;
        }
    }
    else if ((match = Regex.Match(input, range)).Success)
    {
        extractedField = match.Groups[1].Value;
        type = Type.Range;
    }
    else
    {
        //Nothing 
    }
    return extractedField;
}

Вывод данных испытаний OP:

Field is: Email and Type is: Error
Field is: Username and Type is: Error
Field is: InsertDate and Type is: Date
Field is: Age and Type is: Range

Отредактировано: Добавлен пример кода для скрипки Ссылка на скрипку

1 голос
/ 01 марта 2020

Мне кажется, я понял ваш запрос. Вы хотите проверить, какому "выражению" соответствует текущее сообщение, и в зависимости от него установить соответствующий флаг в значение 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);
}

Демонстрационный код

Приведенный выше код использует Regex для поиска соответствующее совпадение.

Пример вывода

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);
}
0 голосов
/ 01 марта 2020

Попробуйте следующее:

    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;
        }
    }
...