// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.DataTypes.TimexExpression { public static class TimexRegex { private const string DateTimeCollectionName = "datetime"; private const string DateCollectionName = "date"; private const string TimeCollectionName = "time"; private const string PeriodCollectionName = "period"; private static IDictionary timexRegex = new Dictionary { { DateCollectionName, new Regex[] { // date new Regex(@"^(XXXX|(?\d\d\d\d))-(?\d\d)(-(?\d\d))?"), new Regex(@"^XXXX-WXX-(?\d)"), new Regex(@"^XXXX-XX-(?\d\d)"), // daterange new Regex(@"^(?\d\d\d\d)"), new Regex(@"^(XXXX|(?\d\d\d\d))-(?\d\d)-W(?\d\d)"), new Regex(@"^(XXXX|(?\d\d\d\d))-(?\d\d)-WXX-(?\d{1,2})(-(?\d))?"), new Regex(@"^(?SP|SU|FA|WI)"), new Regex(@"^(XXXX|(?\d\d\d\d))-(?SP|SU|FA|WI)"), new Regex(@"^(XXXX|(?\d\d\d\d))-W(?\d\d)(-(?\d)|-(?WE))?"), } }, { TimeCollectionName, new Regex[] { // time new Regex(@"T(?\d\d)Z?$"), new Regex(@"T(?\d\d):(?\d\d)Z?$"), new Regex(@"T(?\d\d):(?\d\d):(?\d\d)Z?$"), // timerange new Regex(@"^T(?DT|NI|MO|AF|EV)$"), } }, { PeriodCollectionName, new Regex[] { new Regex(@"P(?\d*\.?\d+)(?Y|M|W|D|WE|WD)$"), new Regex(@"^PT(?\d*\.?\d+)H(\d*\.?\d+(M|S)){0,2}$"), new Regex(@"^PT(\d*\.?\d+H)?(?\d*\.?\d+)M(\d*\.?\d+S)?$"), new Regex(@"^PT(\d*\.?\d+(H|M)){0,2}(?\d*\.?\d+)S$"), } }, }; public static bool Extract(string name, string timex, IDictionary result) { var lowerName = name.ToLower(CultureInfo.InvariantCulture); var nameGroup = new string[lowerName == DateTimeCollectionName ? 2 : 1]; if (lowerName == DateTimeCollectionName) { nameGroup[0] = DateCollectionName; nameGroup[1] = TimeCollectionName; } else { nameGroup[0] = lowerName; } var anyTrue = false; foreach (var nameItem in nameGroup) { foreach (var entry in timexRegex[nameItem]) { if (TryExtract(entry, timex, result)) { anyTrue = true; } } } return anyTrue; } private static bool TryExtract(Regex regex, string timex, IDictionary result) { var regexResult = regex.Match(timex); if (!regexResult.Success) { return false; } foreach (var groupName in regex.GetGroupNames()) { result[groupName] = regexResult.Groups[groupName].Value; } return true; } } }