Twitter(X)の動画URLには、動画の解像度情報が含まれている。
この情報を正規表現で抽出する実装をまとめる。
実装
interface MediaSize { height: number; width: number;}
function extractVideoSize(url: string): MediaSize | undefined { const sizeRegex = /\/(\d+)x(\d+)\//; const match = url.match(sizeRegex);
if (match && match[1] && match[2]) { const width = parseInt(match[1], 10); const height = parseInt(match[2], 10); return { width, height }; }
return undefined;}ポイント
正規表現/\/(\d+)x(\d+)\//でURLから1080x1920のような部分を抽出する。
マッチした場合はparseIntで数値に変換して返す。マッチしない場合はundefinedを返す。
実行例
const inputs = [ "https://video.twimg.com/ext_tw_video/1111/pu/vid/avc1/1080x1920/1.mp4", "https://video.twimg.com/ext_tw_video/1111/pu/pl/1.m3u8"];
console.log(extractVideoSize(inputs[0]));// { width: 1080, height: 1920 }
console.log(extractVideoSize(inputs[1]));// undefinedmp4のURLには解像度情報が含まれているが、m3u8のプレイリストURLには含まれていないためundefinedが返る。
まとめ
Twitter動画URLから解像度を抽出する実装は、正規表現で簡単に実現できる。
動画のプレビューやサムネイル生成時に、事前にサイズ情報を取得したい場合に活用できる。
hsb.horse