February 9, 2020

Sample Regular Expression

[TestMethod]
public void ParseVideoFileForDateTime2Test()
{
    var filePath = @"D:\Temp\Nokia 6\Photos\OpenCamera\VID_20190623_085427.mp4";
    var fileNameSansExt = Path.GetFileNameWithoutExtension(filePath);

    var dateTimeFormat = "yyyyMMdd_HHmmss";
    var result = string.Empty;
    Regex regExp = null;
    CalcRegExpForDateTimeFormat(dateTimeFormat, out regExp);
    if (regExp != null)
    {
        result = regExp.MatchFirstRegExp(fileNameSansExt);
    }
    Assert.IsNotNull(regExp);
    Assert.IsTrue(result.Length == 15);
    Assert.IsTrue(result == "20190623_085427");
}

private static bool CalcRegExpForDateTimeFormat(
    string dateTimeFormat, out Regex regExp)
{
    var res = false;
    regExp = null;
    var newRegex = new StringBuilder(dateTimeFormat.Length);
    foreach (var ch in dateTimeFormat)
    {
        if ((ch == 'y') || (ch == 'M') || (ch == 'd') ||
            (ch == 'H') || (ch == 'm') || (ch == 's'))
        {
            newRegex.Append(@"\d");
        }
        else
        {
            newRegex.Append(ch);
        }
    }
    var regexStr = newRegex.ToString();
    res = (regexStr.Length > 0);
    if (res)
    {
        regExp = new Regex(regexStr, RegexOptions.Compiled);
    }
    return res;
}

public static class RegularExpressionExtensions
{
/// <summary>
/// Match the first occurance of a regular expression in a target string.
/// </summary>
/// <param name="target">string to search</param>
/// <param name="regexp">regular expression object to use for the
/// search</param>
/// <returns>first match of the regular expression otherwise an 
/// empty string if there is no match</returns>
  public static string MatchFirstRegExp(this Regex reg, string target)
  {
    var result = "";
    MatchCollection mc = reg.Matches(target);
    if (mc.Count > 0)
    {
        result = mc[0].Value;
    }
    return result;
  }
}

No comments: