/// <summary> /// 指定されたパスを指定されたパターンで解析し、パラメーターのコレクションを返します。 /// </summary> /// <example> /// var result = PathMapper.Parse("/ServiceUnit/Member/V1/Admin", /// "/ServiceUnit/{ServiceUnitName}/{Version}/{Role}") /// //ServiceUnitName = Member /// //Version = V1 /// //Role = Admin /// </example> /// <param name="path">解析対象のパス</param> /// <param name="pattern">解析するパターン</param> /// <returns>パラメーターのコレクションを含む <see cref="PathMapResult"/> </returns> public static PathMapResult Parse(string path, string pattern) { var result = new PathMapResult(); result.Path = path; var regexText = regexPool.GetOrAdd(pattern, (p) => { return(CreateRegexFromPattern(p)); }); var regex = new Regex(regexText, RegexOptions.Compiled); var match = regex.Match(path); if (!match.Success) { result.Success = false; return(result); } var groupNames = regex.GetGroupNames(); foreach (var groupName in groupNames.Where(s => s != "0")) { result.Parameters.Add(groupName, match.Groups[groupName].Value); } result.Success = true; return(result); }
/// <summary> /// 指定されたパラメーターの値をパターンに適用します。 /// </summary> /// <example> /// var parameter = new Dictionary<string, string>() /// { /// { "ServiceUnitName", "Member" }, /// { "Version", "V1" }, /// { "Role", "Admin" } /// }; /// PathMapper.Map(parameter, "/ServiceUnit/{ServiceUnitName}/{Version}/{Role}"); /// //"/ServiceUnit/Member/V1/Admin" /// </example> /// <param name="parameter">パラメーター</param> /// <param name="mapPattern">適用するパターン</param> /// <returns>適用後の値を含む <see cref="PathMapResult"/> </returns> public static PathMapResult Map(IDictionary <string, string> parameter, string mapPattern) { var result = new PathMapResult(); var regex = new Regex("{(?<key>[A-Za-z]+?)(\\s*:\\*\\s*)?}", RegexOptions.Compiled); var hasParameter = true; var mapPath = regex.Replace(mapPattern, match => { var key = match.Groups["key"].Value; if (parameter.ContainsKey(key)) { return(parameter[key]); } hasParameter = false; return(match.Value); }); result.MappedPath = mapPath; result.Success = hasParameter; return(result); }