ipconfigコマンドの出力から「IPv4 Address … : 192.168.250.100」のような文字列を抽出するプログラムを作成しました。
gオプションを付けると()が無視されちゃう
IPアドレスを含む文字列を探し出すために「IPv4 Address」という文字列を含めて検索しますが、最終的に欲しいのは「192.168.250.100」のようなIPアドレスの部分だけです。
["192.168.250.100", "192.168.100.250"] のような配列が欲しいのです。
gオプションを付けた時のmatchの結果がイメージしていた内容と違っていたので、少し戸惑いました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const p = Deno.run({ | |
cmd: ["cmd", "/C", "chcp 65001 & ipconfig"], | |
stdout: "piped" | |
}) | |
const o = await p.output() | |
const text = new TextDecoder().decode(o) | |
const arr = [] | |
const m = match(text, /IPv4 Address[^:]+:[^\d]+([.\d]+)/g) | |
if(!m){Deno.exit()} | |
for(let i=0; i < m.length ;i++){ | |
arr.push(m[i][1]) | |
} | |
console.log(arr.join('\n')) | |
function match(str:String, re:RegExp){ | |
// 例えば/a(bc)/の場合、結果は["abc","bc"]のようになるが | |
// /a(bc)/gの場合、結果は「"abc", "abc", "abc"…」となってしまう。 | |
// gオプションと「()」を併用したい場合、2回に分けてmatchする必要がある。 | |
// それを1回で出来るようにするための関数。 | |
const m = str.match(re) | |
if(!m){return m} | |
const arr = [] | |
const re2 = new RegExp(re.source) | |
for(let i=0; i<m.length ;i++){ | |
const m2 = m[i].match(re2) | |
if(!m2){continue} | |
arr.push(m2) | |
} | |
return arr | |
} |
0 件のコメント:
コメントを投稿