はてなブログに Markdown 書式で記事を書いているときに、その Markdown を別のプラットフォームで使いたい。そういうこともあると思います。
その際、記事の文章は特に問題ないと思いますが、画像ですね。画像の部分だけ差し替えるコードを書きました。書き換える要素については以前に記事を書いたこれです。 rksoftware.hatenablog.com
■ 本当は
本当は PowerShell で一行で書きたかったのですが、どうも頑張っても無理で、あきらめて C# で長いコードを書きました。
Copilot にも頼って数時間頑張ったのですが......。Copilot ができるという通りに動かず。
■ C# コード
ファイルのパスを受け取って、ファイルを読んで別のファイルに書き出しています。ファイルを読む部分や書く部分を呼び出し元のコマンドに任せることも考えたのですが、PowerShell を考えると、一行が長いファイルに不安もあるし、C# の方で読んでしまう方針で行きます。
using System.Text.RegularExpressions; var inputPath = args.FirstOrDefault() ?? string.Empty; if (!File.Exists(inputPath)) return; var outPath = OutPath(inputPath); if (File.Exists(outPath)) return; var inputText = File.ReadAllText(inputPath); var outputText = ReplaceTag(inputText); File.WriteAllText(outPath, outputText); static string ReplaceTag(string src) => Regex.Matches(src, C.Pattern).Select(MatchToTag).Aggregate(src, (ag, m) => ag.Replace(m.Key, m.Value)); static KeyValuePair<string, string> MatchToTag(Match m) { var (id, dt, ext) = (m.Groups["id"].Value, m.Groups["dt"].Value, m.Groups["ext"].Value); var (id1, date) = (new String(id.Take(1).ToArray()), new String(dt.Take(8).ToArray())); C.Extensions.TryGetValue(ext, out var extension); var url = string.Format(C.FormatUrl, id1, id, date, dt, extension); var tag = string.Format(C.FormatTag, url); return new KeyValuePair<string, string>(m.Value, tag); } static string OutPath(string inputPath) => Path.Combine(Path.GetDirectoryName(inputPath)!, $"__2__{Path.GetFileName(inputPath)}"); static class C { internal static string Pattern => "\\[f:id:(?<id>\\w+):(?<dt>\\d{14})((?<ext>p|b|j)):.*\\]"; internal static string FormatUrl => "https://cdn-ak.f.st-hatena.com/images/fotolife/{0}/{1}/{2}/{3}.{4}"; internal static string FormatTag => ""; internal static System.Collections.ObjectModel.ReadOnlyDictionary<string, string> Extensions => new(new Dictionary<string, string> { {"p","png" }, {"b","bmp" }, {"j","jpg" }, }); }
■ 長いですね
長いコードですね。C# ちからの低さを痛感します。精進。