Created
July 10, 2020 04:47
-
-
Save sharapeco/fc9f4d7bf205b9741b84d9f839ca5aed to your computer and use it in GitHub Desktop.
テキスト中から数値っぽいものを取り出して合計を求める
This file contains hidden or 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
<?php | |
/** | |
* numsum | |
* | |
* テキスト中から数値っぽいものを取り出して合計を求める | |
* | |
* Created at 2020-07-10 | |
*/ | |
$lines = []; | |
while (!feof(STDIN)) { | |
$line = fgets(STDIN); | |
$lines[] = $line; | |
} | |
// 数値っぽい正規表現 | |
$sign = '(?:[+-]?)'; | |
$digits = '(?:[0-9.,])'; | |
$exponent = "(?:[Ee]{$sign}{$digits}+)"; | |
$numRE = "/\\b{$sign}{$digits}+{$exponent}?\\b/"; | |
/** @var array{0:float,1:string} 検出された数値 */ | |
$values = []; | |
$sum = 0; | |
foreach ($lines as $line) { | |
if (preg_match_all($numRE, $line, $matches)) { | |
foreach ($matches[0] as $expr) { | |
$value = floatval($expr); | |
$values[] = [$value, $expr]; | |
$sum += $value; | |
} | |
} | |
} | |
echo implode('', $lines); | |
echo PHP_EOL; | |
echo implode(' + ', array_map(function($value) { | |
return '(' . $value[1] . ')'; | |
}, $values)); | |
echo ' =', PHP_EOL; | |
echo '計 ' . $sum, PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Xyzzy の filter-region や filter-buffer で使用することを想定
See: Atom Editor に xyzzy の filter-buffer 機能をつける - メモ用紙